一、@value注解
@Value("${key}") , key 来自 application.properties(yml)
项目结构
![](https://img-blog.csdnimg.cn/aa8999c626c240bb90a8a8759d5c6aed.png)
1.首先在核心配置文件application.properties中编写key=value格式的数据
#配置端口号
server.port=8082
#context-path
server.servlet.context-path=/myboot
#自定义key=value
school.name=清华大学
school.website=www.tsinghua.edu.cn
school.address=北京海淀区
site=www.baidu.com
2.编写controller包下的HelloContoller类
package com.it.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;
@Value("${server.servlet.context-path}")
private String contextPath;
@Value("${school.name}")
private String name;
@Value("${site}")
private String site;
@RequestMapping(value = "/data")
@ResponseBody
public String queryData(){
return name+",site="+site+",项目的访问地址="+contextPath+",使用的端口="+port;
}
}
3.运行Application类的项目主函数,自动运行项目
项目结果
二、@ConfigurationProperties 注解
将整个文件映射成一个对象,用于自定义配置项比较多的情况
在 com.bjpowernode.springboot.config 包下创建 SchoolInfo 类,并为该 类加上Component 和 ConfigurationProperties 注解,prefix 可以不指定,如果不指定,那么
会去配置文件中寻找与该类的属性名一致的配置,prefix 的作用可以区分同名配置
1.SchoolInfo类
package com.it.entity;
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;
@Override
public String toString() {
return "SchoolInfo{" +
"name='" + name + '\'' +
", website='" + website + '\'' +
", address='" + 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;
}
}
2.controller包下的SchoolController类
package com.it.controller;
import com.it.entity.SchoolInfo;
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;
import javax.annotation.Resource;
@Controller
public class HelloController {
@Resource
private SchoolInfo info;
@RequestMapping(value = "/info")
@ResponseBody
public String queryInfo(){
return "SchoolInfo对象=="+info.toString();
}
}
运行程序
三、警告解决
在 SchoolInfo 类中使用了 ConfigurationProperties 注解,IDEA 会出现一个警告,不影响程序的执行 。
点击 open documentnation 跳转到网页,在网页中提示需要加一个依赖,我们将这个依赖拷贝,粘贴到 pom.xml 文件中 。