Register a Properties File via Java Annotations
@PropertySource annotation, it is introduced since Spring 3.1, and used in conjunction with Java-based configuration and the @Configuration annotation.
Another useful way to register a new properties file is by using a placeholder, which allows us to dynamically select the right file at runtime.
${envTarget:mysql}
Defining Multiple Property Locations
The @PropertySource annotation is repeatable according to Java 8 conventions. We can define multiple properties files and their locations.
We can specify an array of @PropertySource; this works in any Java version.
Using/Injecting Properties
Injecting a property using the @Value annotation.
?? specify a default value for the property.
We can obtain the value of a property using the Environment API
@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.rul));
Properties with Spring Boot
Default Property File
This new support involves less configuration compared to standard Spring.
application.properties: the Default Property File; doesn't need any arrangement
Environment-Specific Properties File
If we need to target different environments, application-environment.properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.
if we define a "staging" environment, we then have to define a stagging profile, and then application-stagging.properties.
This env file will be loaded and will take precedence over the default property file.
Test-Specific Properties File
Spring boot looks for test specific files in our src/test/resources directory during a test run. Again, default properties will still be injectable as normal but will be overridden by these test specific properties if there is a collision.
@Runwith(SpringRunner.class)
@TestPropertySource("/foo.properties")
if we don't want to use a file, directly specify names and values.
@TestPropertySource(properties={"foo=bar"})
or it can achieve the same using
@RunWith(SpringRunner.class)
@SpringBootTest(
properties={"foo=bar"},classes=SpringBootPropertiesTestApplication.class)
)
Hierarchical Properties
we can mapping a group of properties from a file into a POJO, using @ConfiguartionProperties annotation.
Properties from Command Line Arguments
java -jar app.jar --property="value"
or via system properties, which are provided before the -jar command rather than after it
java -Dproperty.name="value" -jar app.jar
Properties from Environment Variables
export name=value
java -jar app.jar