1. @value注解
可以从配置文件中读取属性值(使用springEL表达式)
例:
application.yml:
#开发环境
spring:
profiles:
active: dev
Demo代码:
@RestController
public class HelloController {
@Value("${spring.profiles.active}")
private String active;
@RequestMapping("hello")
public String hello(){
return active;
}
}
测试结果:
2. 使用spring Environment 访问配置信息
@Autowired
private Environment environment;
@RequestMapping("hello")
public String hello(){
return environment.getProperty("spring.profiles.active");
}
3. @PropertySource注解
加载指定的 *.properties 到 Spring 的 Environment 中
也可配合@value使用
例:
创建 *.properties
添加属性: demo.msg=hhhhhhhhhhh
@RestController
@PropertySource(value = {"classpath:/properties/parameter.properties"})
public class HelloController {
@Value("${demo.msg}")
private String active;
@Autowired
private Environment environment;
@RequestMapping("hello")
public String hello() {
return "@value: " + active + " ; " + "environment: " + environment.getProperty("demo.msg");
}
}
测试效果: