【spring Boot】spring boot1.5以上版本@ConfigurationProperties取消location注解后的替代方案


前言

===========================================

初步接觸Spring Boot

===========================================

資源文件中自定義屬性值,配置在一個對象bean上,然后在程序中可以使用bean的屬性值。

 一。

 

 

二。

@Component
標志本類為一個bean
@PropertySource(value = "classpath:/application.properties")
指定綁定哪個資源文件,【如果要綁定自定義的資源文件中的值的話,是可以用上的】這里的application.properties文件是springboot默認的資源文件,是可以不用指定的,這里綁定的話,會去加載綁定兩次。

@ConfigurationProperties(prefix = "com.sxd")
指定綁定資源文件中前綴以com.sxd開頭的屬性名,其他的不會綁定過來。因為這里location屬性取消了,所以采用上面注解進行替代方案

 

package com.sxd.beans;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = "classpath:/application.properties")
@ConfigurationProperties(prefix = "com.sxd")
public class ConfigBean {

    private String name;
    private String want;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWant() {
        return want;
    }

    public void setWant(String want) {
        this.want = want;
    }


}
View Code

 

 

三。

@EnableConfigurationProperties(ConfigBean.class)
激活綁定的bean

@Autowired
將綁定的某個bean自動注入

 

 

package com.sxd.firstdemo;

import com.sxd.beans.ConfigBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
@EnableConfigurationProperties(ConfigBean.class)
public class FirstdemoApplication {

    @Autowired
    ConfigBean configBean;

    @RequestMapping("/")
    public String index(){

        return "Hello Spring Boot,"+configBean.getName();
    }
    public static void main(String[] args) {
        SpringApplication.run(FirstdemoApplication.class, args);
    }
}
View Code

 

 四。

運行結果:

 


免責聲明!

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



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