springboot 获取.yml中自定义参数

需求:根据不同环境获取到不同的参数,放在.yml中方便修改!


在开发环境中,回调的url地址


在测试环境中,回调的url地址


在生产环境中,回调的url地址


我是通过2种方式来实现的

一:通过@Value获取:代码如下


 

package com.heque.service.pay;

import org.springframework.beans.factory.annotation.Value;

public abstract class ObtainNotifyUrl {

    @Value("${weixinAndAli.wechatNotifyUrl}")
    private String wechatNotifyUrl;
    @Value("${weixinAndAli.aliNotifyUrl}")
    private String aliNotifyUrl;

    public String getWechatNotifyUrl() {
        return wechatNotifyUrl;
    }

    public void setWechatNotifyUrl(String wechatNotifyUrl) {
        this.wechatNotifyUrl = wechatNotifyUrl;
    }

    public String getAliNotifyUrl() {
        return aliNotifyUrl;
    }

    public void setAliNotifyUrl(String aliNotifyUrl) {
        this.aliNotifyUrl = aliNotifyUrl;
    }
}


 

package com.heque.service.pay;

import org.springframework.stereotype.Component;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
@Component
public class Test extends ObtainNotifyUrl{

    
}


通过springframework自动包可以完成此功能,需要注意Test继承对象需要加入@component,把对象交给springContainer去管理,我们需要的时候只需注入资源就好了。
@Autowired private Test test; test.getAliNotifyUrl();/test.getWechatNotifyUrl();

 

二:通过@ConfigurationProperties(prefix = "weixinAndAli")注解,代码如下


 

package com.heque.service.pay;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author: TimBrian
 * @date: Sep 10, 2018 9:13:40 AM      
 */
@Component
@ConfigurationProperties(prefix = "weixinAndAli")
public class ConfigUtils {
    
    private String wechatNotifyUrl;
    
    private String aliNotifyUrl;
    
    public String getWechatNotifyUrl() {
        return this.wechatNotifyUrl;
    }

    public void setWechatNotifyUrl(String wechatNotifyUrl) {
        this.wechatNotifyUrl = wechatNotifyUrl;
    }

    public String getAliNotifyUrl() {
        return aliNotifyUrl;
    }

    public void setAliNotifyUrl(String aliNotifyUrl) {
        this.aliNotifyUrl = aliNotifyUrl;
    }
}


调用和方法一一样的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值