从配置文件中取数据
设置数据:
#配置端口号
server.port=8082
#context-path
server.servlet.context-path=/myboot
#自定义key=value
school.name=动力节点
school.website=www.bjpowernode.com
school.address=北京大兴区
site=www.baidu.com
在Controller中获取值:
package com.example.Controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
//获取值
@Value("${server.port}")
private Integer port;
//这个时候application.properties里定义的server.port的值就赋值给了port
@Value("${server.servlet.context-path}")
private String contextPath;
@Value("${school.name}")
private String name;
@Value("${school.website}")
private String website;
@Value("${site}")
private String site;
@RequestMapping("/data")
@ResponseBody
public String queryData(){
return name+",site"+site+",项目的访问地址:"+contextPath+",我们使用的端口:"+port;
}
}
结果
二、把配置文件的数据映射为java对象
package com.example.vo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {
private String name;
private String website;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "SchoolInfo{" +
"name='" + name + '\'' +
", website='" + website + '\'' +
", address='" + address + '\'' +
'}';
}
}
其中@Component是创建子类对象
@ConfigurationProperties(prefix = "school")是从配置文件中找到school开头的值
在Controller中调用(其中@Resource表示自动注入,先byname,再bytype)
27 手工获取容器中对象,早springboot中使用ApplicationContext