大家好,我是网创有方。这节实现的效果是通过代码灵活地调用application.properties实现配置类参数赋值。
第一步:编写配置类
package cn.wcyf.wcai.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;@Configuration //声明是个配置类
public class WechatConfig {public String getAppId() {return appId;}public void setAppId(String appId) {this.appId = appId;}public String getToken() {return token;}public void setToken(String token) {this.token = token;}public String getSecretKey() {return secretKey;}public void setSecretKey(String secretKey) {this.secretKey = secretKey;}private String appId;private String token;private String secretKey;
}
第二步:编写application.properties
spring.application.name=wcai
server.port=80
#用于配置请求controller的path前缀,比如/demo,就是在请求前面加上/demo,留空就不加
server.servlet.context-path=
wechat.app-id=wx4dqdadqqdq
wechat.token=da6644qd44ad72q
wechat.secret-key=7a78d57q4523szd45357
第三步:编写 Controller,通过environment的getProperty动态获取application.properties的参数
@RestController
public class HellowordController {@ResourceApplicationContext applicationContext;@RequestMapping("/helloword")public String getHelloword(){return "helloword";}@RequestMapping("/getWechatConfig")public WechatConfig getWechatSetting(){Environment enr = applicationContext.getEnvironment();String appId = enr.getProperty("wechat.app-id");String token = enr.getProperty("wechat.token");String secret_key = enr.getProperty("wechat.secret-key");WechatConfig wechatSetting = new WechatConfig();wechatSetting.setAppId(appId);wechatSetting.setToken(token);wechatSetting.setSecretKey(secret_key);return wechatSetting;}
}
运行效果:
个人感觉这种方式还是没有上节的自动配置方法好用。第十节:学习ConfigurationProperties类来配置pojo实体类参数(自学Spring boot 3.x的第二天)-CSDN博客