獲取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

