第十一节:学习通过动态调用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 {
    @Resource
    ApplicationContext 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博客

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mero技术博客

创作不易,打赏小弟可否

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值