大家好,我是網創有方。這節實現的效果是通過代碼靈活地調用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博客