SpringBoot注解配置文件映射属性和实体类

一、创建pay.properties文件(注意放在resources文件夹下)
在这里插入图片描述

两种方式:
第一种:Controller直接引用
第二种:编写配置类

第一种

二、添加引用注释:@PropertySource
代码:

@RestController
@RequestMapping("/api/v1/pub/test")
@PropertySource(value = "classpath:pay.properties")
public class TestController {
    @Value("${wxpay.appid}")
    private String payAppid;
    @Value("${wxpay.secret}")
    private String paySecret;
    @Value("${wxpay.mechid}")
    private String payMechid;

    @GetMapping("listpay")
    public JsonData listpay(){
        Map<String,String> map=new HashMap<>();
        map.put("wxpay.appid",payAppid);
        map.put("wxpay.secret",paySecret);
        map.put("wxpay.mechid",payMechid);
        return JsonData.buildSuccess(map);
    }
}

运行截图:
在这里插入图片描述
第二种:
1.编写配置类,添加配置文件注释:@Configuration
2.配置类,添加引用注释@PropertySource(value=“classpath:xxxx.properties”)
3.Contoller调用配置类获取数据

代码:配置类

@Configuration
/**
*@PropertySource(value = "classpath:pay.properties")
*使用 @ConfigurationProperties 注解,设置相关属性;当配置文件很多时使用
*/
@ConfigurationProperties(prefix="test")
public class PayConfig_test {
    @Value("${wxpay.appid}")
    private  String payAppid;
    @Value("${wxpay.secret}")
    private  String paySecret;
    @Value("${wxpay.mechid}")
    private  String paymechid;

    public String getPayAppid() {
        return payAppid;
    }

    public void setPayAppid(String payAppid) {
        this.payAppid = payAppid;
    }

    public String getPaySecret() {
        return paySecret;
    }

    public void setPaySecret(String paySecret) {
        this.paySecret = paySecret;
    }

    public String getPaymechid() {
        return paymechid;
    }

    public void setPaymechid(String paymechid) {
        this.paymechid = paymechid;
    }
}

代码:Controller

@RestController
@RequestMapping("/api/v1/pub/test")
@PropertySource(value = "classpath:pay.properties")
public class TestController {
    @Autowired
    private PayConfig_test payConfig_test;
    @GetMapping("listpay")
    public JsonData listpay(){
        Map<String,String> map=new HashMap<>();
        map.put("wxpay.appid",payConfig_test.getPayAppid());
        map.put("wxpay.secret",payConfig_test.getPaySecret());
        map.put("wxpay.wechid",payConfig_test.getPaymechid());
        return JsonData.buildSuccess(map);
    }
}

运行结果:
在这里插入图片描述

------------------------------------------------------------------------------------------------------------------------------------------------------------------------自学习

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值