Externally defined values such as usernames, passwords, file paths,
and the like may be accessed using @ExternalValue
and one or more of JavaConfig's ValueSource annotations.
@Configuration @PropertiesValueSource("classpath:com/acme/db.properties") public class AppConfig { @ExternalValue("datasource.username") String username; @Bean public TestBean testBean() { return new TestBean(username); } }
com/acme/db.properties will be read from the classpath
and the value associated with key datasource.username
will be injected into the username field. The contents
of db.properties might be as follows:
datasource.username=scott
datasource.password=tiger
...
![]() | Note |
|---|---|
An array of properties file locations may be supplied to
@Configuration
@PropertiesValueSource({"classpath:com/acme/a.properties", "file:/opt/acme/b.properties"})
public class AppConfig {
// ...
}
|
@ExternalValue may also be used as a method-level annotation
@Configuration @PropertiesValueSource("classpath:com/acme/db.properties") public abstract class AppConfig { @ExternalValue("datasource.username") abstract String username(); @Bean public TestBean testBean() { return new TestBean(username()); } }
The primary advantage to using @ExternalValue methods is that
rather than injecting the external value just once (as is done in the case
of @ExternalValue fields), @ExternalValue methods
are evaluated every time they're referenced. As this is not usually required,
@ExternalValue fields are the preferred method. A downside of
@ExternalValue methods is that they should be abstract, requiring
you to declare the entire @Configuration class abstract, and this is not
in alignment with the semantics users typically associate with using the
abstract keyword.