@ConfigurationProperties 注解将配置文件参数转化给Bean属性
一、application.properties参数配置
website.ip=192.168.10.112
website.port=8725
website.name=catlina.com
二、创建实体类 WebSiteProperties ,设置属性ip、port、name。在类上配置@Configuration 和 @ConfigurationProperties(prefix = “website”)注解。
@ConfigurationProperties配置前缀值与application.properties里参数前缀保持一致。添加类的setter、getter方法
package com.jvli.project.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "website")
public class WebSiteProperties {
private String ip;
private Integer port;
private String name;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "WebSiteProperties [ip=" + ip + ", port=" + port + ", name=" + name + "]";
}
}
三、创建Controller测试,注入WebSiteProperties 。此时我们便可以任性的运用配置文件里的参数了。实际开发中结合自己的业务实现不同的应用场景。
package com.jvli.project.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.jvli.project.config.WebSiteProperties;
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private WebSiteProperties webSiteProperties;
@RequestMapping(value = "/print/property",method = RequestMethod.GET)
public Map<String, Object> printProperty() {
System.out.println(webSiteProperties);
Map<String, Object> webSiteMap = new HashMap<>();
webSiteMap.put("ip", webSiteProperties.getIp());
webSiteMap.put("port", webSiteProperties.getPort());
webSiteMap.put("name", webSiteProperties.getName());
return webSiteMap;
}
}
查看控制台和postman调用返回结果