欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > 第十一节:学习通过动态调用application.properties参数配置实体类(自学Spring boot 3.x的第二天)

第十一节:学习通过动态调用application.properties参数配置实体类(自学Spring boot 3.x的第二天)

2025/9/14 19:46:59 来源:https://blog.csdn.net/qq_21004057/article/details/140060483  浏览:    关键词:第十一节:学习通过动态调用application.properties参数配置实体类(自学Spring boot 3.x的第二天)

大家好,我是网创有方。这节实现的效果是通过代码灵活地调用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博客

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词