工具类使用spring注解Value 不生效解决

  1. 类必须使用注解@Component
  2. 使用@PostConstruct   修饰初始化方法带入变量

  3. Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。

    通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:

    Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
     

    package cn.hsa.mbs.ydjy.common.util;
    
    import cn.hsa.cep.plc.std.common.core.utils.StringUtils;
    import cn.hsa.mbs.common.exception.MbsException;
    import cn.hsa.mbs.common.utils.HttpUtil;
    import cn.hsa.mbs.ydjy.common.dto.YdjyResBodyHeader;
    import com.alibaba.fastjson.JSON;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    
    /**
     *异地就医接口请求工具类
     */
    @Component
    @Slf4j
    public class YdjyHttpUtils {
    
        public static YdjyHttpUtils ydjyHttpUtils;
    
        @Value("${ydjy.httpUrl}")
        private  String httpUrl;
    
        @PostConstruct
        public void beforeInit(){
            ydjyHttpUtils = this;
        }
    
        /**
         *@return
         * @param obj    restful 请求地址
         */
        public static YdjyResBodyHeader sendRestfulRequest(Object obj) throws MbsException {
            String results =null;
            try{
                log.info("异地就医请求入参:"+JSON.toJSONString(obj));
                results = HttpUtil.doPostJson(ydjyHttpUtils.httpUrl,JSON.toJSONString(obj));
                log.info("异地就医请求返回:"+results);
            }
            catch (Exception e){
                throw new MbsException("异地就医接口调用失败" + results);
            }
            if(StringUtils.isNullOrEmpty(results))
            {
                throw new MbsException("异地就医接口调用失败,地址:"+YdjyHttpUtils.getHttpUrl());
            }
            YdjyResBodyHeader ydjyResBodyHeader = JSON.parseObject(results, YdjyResBodyHeader.class);
            return  ydjyResBodyHeader;
        }
    
    
        public static String getHttpUrl() {
            return ydjyHttpUtils.httpUrl;
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值