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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM