Man
Man

Reputation: 53

How does Spring know which property file to refer to for getting the value of the variable annotated with @Value?

What if there are multiple property files in our application and both of those files have that variable with different values set?

We usually just inject the value as below and it somehow always manages to get the value form properties file. How?

@Configuration
public class AppConfig {    
    @Value("${spring.datasource.url}")
    private String datasourceUrl;

Upvotes: 1

Views: 3084

Answers (2)

user911651
user911651

Reputation:

The value from the last file that Spring reads will overwrite all previously read values. If you define the order in which files are read yourself (via configuration for example) than you have full control over it. Have a look at the follwing examples:

Annotation based config:

@Configuration
@PropertySource({"classpath:foo.properties", "classpath:bar.properties"})
public class PropertiesWithJavaConfig {
//...
}

XML-based config:

<context:property-placeholder location="classpath:foo.properties,classpath:bar.properties"/>

If bar.properties contains properties which are also defined in foo.properties, the value from bar.properties overwrites the one from foo.properties.

Upvotes: 2

diginoise
diginoise

Reputation: 7620

Spring Boot has many possible sources of configuration.

When it comes to property files it checks for application.properties and then application-<active_profile>.properties where <active_profile> is set by spring.profiles.active environment variable (the same holds for *.yaml files).

It will search for property files applying the above rule in the following directories in this precedence:
(higher on the list overrides properties loaded from the lower locations)

  • /config subdirectory of the current directory
  • current ./ directory
  • classpath's /config package (everything in src/main/resources/config if you use maven)
  • classpath's root / (everything in src/main/resources if you use maven)

Upvotes: 4

Related Questions