SpringBoot 官方文档示例:(12)读取配置文件中属性的3种常用方式
原创
©著作权归作者所有:来自51CTO博客作者wx62e0d796b5814的原创作品,请联系作者获取转载授权,否则将追究法律责任
一、SpringBoot读取配置文件里属性的几种方式:
1.通过定义配置类,使用
@Configuration注解和@ConfigurationProperties注解,然后注入该配置类,最后通过配置类的getter方法拿配置
2.通过@value注解
3.通过注入Enviroment bean
二、示例
- application.properties
server.port=9070
username=amadeusliu
password=myPassword
school=tju
2.定义配置类:
package cn.edu.tju.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties
@Configuration
public class MyConfig {
public String username;
public 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;
}
}
3.controller中分别用各种方式获取配置属性
package cn.edu.tju.controller;
import cn.edu.tju.config.MyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.env.Environment;
@RestController
public class TestController {
@Autowired
Environment environment;
@Autowired
private MyConfig myConfig;
@Value("${school}")
private String school;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
@RequestMapping("getSchool")
public String getInfo(){
return getSchool();
}
@RequestMapping("getPassword")
public String getPassword(){
return myConfig.getPassword();
}
@RequestMapping("getVmInfo")
public String getVmInfo(){
return environment.getProperty("java.vm.info");
}
}
4.启动程序,访问网址:
http://localhost:9070/getPassword
http://localhost:9070/getSchool
http://localhost:9070/getVmInfo
输出结果如下: