自定义 properties 文件获取属性
使用
@ConfigurationProperties((prefix = "demo"))
和
@PropertySource("classpath:myconfig.properties")
来批量注值到 bean 中
- @Component
- @ConfigurationProperties(prefix = "com.jy")
- @PropertySource("classpath:myconfig.properties")
- public class TestBean {
- private String bbb;
- public String getBbb() {
- return bbb;
- }
- public void setBbb(String aaa) {
- this.bbb = aaa;
- }
- }
不要忘了 @Component
application.properties 获取属性
application.propertie 中定义一个属性
com.jy.aaa=111
一. 使用 Environment 获取属性
1). 项目主程序中 : 使用 ConfigurableApplicationContext 的 getEnvironment() 方法
- @SpringBootApplication
- public class TestApplication {
- public static void main(String[] args) {
- ConfigurableApplicationContext context = SpringApplication.run(TestApplication.class, args);
- String aaa = context.getEnvironment().getProperty("aaa");
- }
- }
2). 其他类中 : 直接使用 @AutoWired 获取 Environment 对象
- @Autowired
- Environment env;
二. 直接使用 @Value("属性全名") 注值
- @Value("aaa")
- String aaa;
三. 使用 @ConfigurationProperties((prefix = "demo")) 批量注值
- @Component
- @ConfigurationProperties(prefix = "com.jy")
- public class TestBean {
- private String aaa; //getter&setter 方法省略
使用的时候直接 @Auto Wired 获取 TestBean 对象即可
f
来源: http://www.bubuko.com/infodetail-3053986.html