- 创建配置文件:site.properties
site.name = gopher site.url = https://ijackey.com
- 创建获取配置参数的实体类:SiteConfig.java
package com.example.demo.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component // 配置参数的前缀 @ConfigurationProperties(prefix = "site") // 读取指定配置文件 @PropertySource(value = "classpath:site.properties") public class SiteConfig { private String name; private String url; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "SiteConfig{" + "name='" + name + '\'' + ", url='" + url + '\'' + '}'; } }
- 测试,创建文件:SiteController.java
package com.example.demo.controller; import com.example.demo.config.SiteConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/site") public class SiteController { // @AutoWired会帮助我们的变量与配置文件中的内容进行自动匹配 @Autowired SiteConfig sc; @RequestMapping(value = "index") @ResponseBody public String index() { return sc.toString(); } }