One of the ways of configuring Spring applications is using YAML configuration files
.
Spring YAML File
1、Spring profiles help enable Spring Applications
to define different properties
for different environments
.
2、application.yml
relative path is /myApplication/src/main/resources/application.yml
Let’s take a look at a simple YAML file
that contains two profiles. separating by three dashes
.
# application.yml
spring:
config:
activate:
on-profile: test
name: test-YAML
environment: testing
enabled: false
servers:
- www.abc.test.com
- www.xyz.test.com
---
spring:
config:
activate:
on-profile: prod
name: prod-YAML
environment: production
enabled: true
servers:
- www.abc.com
- www.xyz.com
The properties defined in the profile-specific documents won’t be loaded unless we explicitly indicate it.
Binding YAML to a Config Class
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YAMLConfig {
private String name;
private String environment;
private boolean enabled;
private List<String> servers = new ArrayList<>();
// standard getters and setters
}
The annotations used here are:
1、@Configuration
– marks the class as a source of bean definitions
2、@EnableConfigurationProperties
– enable
@ConfigurationProperties
annotated beans in the Spring application
3、@ConfigurationProperties
– binds and validates the external configurations to a configuration class
Accessing the YAML Properties
In the properties file, we’ll set the spring.profiles.active
environment variable to prod
.
If we don’t define this property, only the default
profile will be active.
spring.profiles.active=prod
@SpringBootApplication
public class MyApplication implements CommandLineRunner {
@Autowired
private YAMLConfig myConfig;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MyApplication.class);
app.run();
}
public void run(String... args) throws Exception {
System.out.println("using environment: " + myConfig.getEnvironment());
System.out.println("name: " + myConfig.getName());
System.out.println("enabled:" + myConfig.isEnabled());
System.out.println("servers: " + myConfig.getServers());
}
}
using environment: production
name: prod-YAML
enabled: true
servers: [www.abc.com, www.xyz.com]
YAML Property Overriding
In Spring Boot, YAML files can be overridden by other YAML properties files.
in order of highest precedence first
:
1、Profiles’ properties placed outside the packaged jar
2、Profiles’ properties packaged inside the packaged jar
3、Application properties placed outside the packaged jar
4、Application properties packaged inside the packaged jar