Springboot 獲取yml、properties參數


獲取properties或yml文件的配置數據(兩種方法)(默認的application文件或者自定義的yml和properties)

1、使用@Value()注解
1.1 配置數據
如:在properties.yml文件配置如下數據
    message_zh: 張三
    message_en: ergouzi
在controller中獲取:
1.2 讀取數據
讀取自定義文件:須加注解
@PropertySource(value = {"classpath:config.yml","classpath:config.properties"})

 讀取application文件不需要加注解
// 中文 @Value("${message_zh}") private String message_zh; // 英文 @Value("${message_en}") private String message_en; @RequestMapping(value = "/{id}") public String index(HttpServletRequest request, @PathVariable Integer id){ if (id == 1 ){ request.setAttribute("info",message_zh); }else { request.setAttribute("info", message_en); } return "index"; }

 2、使用 @component
    @ConfigurationProperties(prefix = "user")
    @PropertySource(value = "classpath:myConfig.properties")

首先在myConfig.properties或myConfig.yml中配置參數:
    user.userName = '李二狗'
    user.password = 'admin'

2.1 javabean
/**
 * 〈一句話功能簡述〉<br> 
 * 〈yml或properties配置參數〉
 *
 * @author 丶Zh1Guo
 * @create 2018/11/21
 * @since 1.0.0
 */
@Component                                // 組件
@ConfigurationProperties(prefix = "user")              // 前綴
@PropertySource(value = "classpath:myConfig.properties")    // 自定義配置文件路徑
public class properConfig {
    private String userName;   // 注意要和配置文件一致
    private String password;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
2.2 controller
/**
 * 〈一句話功能簡述〉<br> 
 * 〈〉
 *
 * @author 丶Zh1Guo
 * @create 2018/11/21
 * @since 1.0.0
 */
@restController
public class template {
    @Autowired
    properConfig config;

    @RequestMapping(value = "/config")
    public String config(){
        return config.getUserName();
    }
}

 

 

 

 

總結:

第一種方法適合只取某些數據

第二種方法適合取所有數據

yml和properties區別

yml:    key:(空格)value

properties: key = value

 

 


免責聲明!

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



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