Spring Boot读取配置几种方式
spring读取配置有三种方式,使用@Value,@ConfigurationProperties,@Environment,@PropertySource,除了@PropertySource不支持yml的文件读取,下面我们对这几种方式分别进行介绍
使用@Value
比如我们在application.properties或application.yml中定义了一些配置,如:dynamic.subscribeUrl,在项目中我们只需要使用@Value就可以获取到。
@Component
public class DynamicConfig {
@Value("dynamic.subscribeUrl")
private String subscribeUrl;
}
使用@ConfigurationProperties
上面的例子,我们也可以通过@ConfigurationProperties来实现,只需要指定一个前缀
@Component
@ConfigurationProperties(prefix = "dynamic")
public class DynamicConfig {
private String subscribeUrl;
}
使用@Environment
@Environment可以获取所有加载的配置文件,我们只需要根据getProperty方法就可以获取
@Autowired private Environment environment; environment.getProperty(String key);
使用@PropertySource
我们获取config/flight.properties下所有的配置,前缀以dynamic开头的
@Component
@ConfigurationProperties(prefix = "dynamic")
@PropertySource("config/flight.properties")
public class DynamicConfig {
private String subscribeUrl;
}