5. Working with externalized values
Prev |  | Next

## 5. Working with externalized values

## 5.1. `@ExternalValue`

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.

### 5.1.1. `@ExternalValue` fields

    @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 `@PropertiesValueSource`, and along with `classpath:`, all of the standard Spring resource-loading prefixes are supported, such as `file:` and `http:`.
    @Configuration
    @PropertiesValueSource({"classpath:com/acme/a.properties", "file:/opt/acme/b.properties"})
    public class AppConfig {
        // ...
    }

### 5.1.2. `@ExternalValue` methods

`@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.

Prev |  | Next
4.4. ConfigurationSupport | Home | 5.2. Available ValueSource annotations