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;
    }
}


调用和方法一一样的

猜你喜欢

转载自blog.csdn.net/wang20y8/article/details/82656533
今日推荐