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 注解
将整个文件映射成一个对象,用于自定义配置项比较多的情况
- 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();
- }
-
- }
运行程序

三、警告解决