Configuration File Auto loading - wuyichen24/spring-microservices-in-action GitHub Wiki
Spring has a functionality of loading the parameters from the configuration file to your Java class automatically, whatever the configuration file is an application configuration file or your customized configuration file, or the format is properties (.properties) or YAML (.yml)
Load the application configuration file in the properties format
In your application configuration properties file, you can define your parameters like this: application.properties
redis.server=127.0.0.1
redis.port=6379
In the Java class, you can use @Component
annotation on class level and use @Value
annotation on field level with the name of the parameter in the properties file.
@Component
public class ServiceConfig{
@Value("${redis.server}")
private String redisServer="";
@Value("${redis.port}")
private String redisPort="";
/* omit other methods */
}
In this case, you don't have to implement the functionality of reading properties files and don't have to write the setters methods of the fields in this class too.
Load the application configuration file in YAML format
(Need to add)
Load your customized configuration file
The only differece is you need to add @PropertySource
annotation to your config class for specifying the location and name of your customized config file. The path can be either an absolute path or relative path with classpath parameter, like:
@Component
@PropertySource("classpath:your_customize_config.properties")
public class ServiceConfig{
@Value("${redis.server}")
private String redisServer="";
@Value("${redis.port}")
private String redisPort="";
/* omit other methods */
}