SpringBoot 获取properties配置文件的属性

时间:2023-03-10 02:39:19
SpringBoot 获取properties配置文件的属性

自定义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