1.使用@Value注解
使用@Value注解加载单个属性值
如果在yaml或者properteis中存在配置:
baidu.token = h4f644y9e4th64kyukl4uil4td4f3h
baidu.username = 157562358985
@Component("policyCheck1001")
@Slf4j
public class PolicyCheck1001 implements PolicyCheckHandler {
//读取配置文件中baidu.token 的值
@Value("${baidu.token}")
private String token;
//读取配置文件中baidu.username 的值
@Value("${baidu.username}")
private String username;
}
2.使用@ConfigurationProperties注解
使用@ConfigurationProperties注解可以加载一组属性的值,针对于要加载的属性过多的情况,比@Value更加简洁。
如果在yaml或者properteis中存在配置:
baidu.token = h4f644y9e4th64kyukl4uil4td4f3h
baidu.username = 157562358985
@Component
@Slf4j
@ConfigurationProperties(prefix ="baidu") //指定加载配置的前缀
public class BaiDuConfig {
private String token;
private String username;
}
3.读取指定文件中的内容@PropertySource+@Value
有些时候我们需要从自己定义的配置文件中加载属性值,这个时候就需要用@PropertySource+@Value注解来配合使用了。
如resources目录下存在Config.properties文件,需要加载其中的token和username属性:
@Component
@Slf4j
@PropertySource(value = {"Config.properties"}) //指定加载配置的前缀
public class BaiDuConfig {
//读取配置文件中baidu.token 的值
@Value("${baidu.token}")
private String token;
//读取配置文件中baidu.username 的值
@Value("${baidu.username}")
private String username;
}
这里需要注意的是@PropertySource是用来加载我们自定义的properties文件的。针对yaml文件不生效。
4.读取指定文件中的内容@PropertySource+@ConfigurationProperties
如resources目录下存在Config.properties文件,需要加载其中的token和username属性:
@Component
@Slf4j
@ConfigurationProperties(prefix ="baidu")
@PropertySource(value = {"Config.properties"}) //指定加载配置的前缀
public class BaiDuConfig {
//读取配置文件中baidu.token 的值
private String token;
//读取配置文件中baidu.username 的值
private String username;
}
5.使用springBoot的Environment接口获取配置
Environment这个接口我们平时不是很常用,但是这是spring很重要的一个接口。
org.springframework.core.env.Environment是当前应用运行环境的公开接口,主要包括应用程序运行环境的两个关键方面:配置文件(profiles)和属性。Environment继承自接口PropertyResolver,而PropertyResolver提供了属性访问的相关方法。这篇文章从源码的角度分析Environment的存储容器和加载流程,然后基于源码的理解给出一个生产级别的扩展。
我们可以debug看一下Environment的内容:
@Slf4j
@RestController
@RequestMapping("/hello")
public class BaiDuConfig {
@Autowired
private Environment environment;
@RequestMapping("/test002")
public void test04(){
//通过Environment获取配置
String property = environment.getProperty("baidu.token");
System.out.println(property);
}
}