博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot使用@Value从yml文件取值为空--注入静态变量
阅读量:4703 次
发布时间:2019-06-10

本文共 1446 字,大约阅读时间需要 4 分钟。

SpringBoot使用@Value从yml文件取值为空--注入静态变量

1.application.yml中配置内容如下:

  1.  
    pcacmgr:
  2.  
    publicCertFilePath: E:\\pcacmgr\\CerFiles\\xh_public.cer
  3.  
    encPublicCertFilePath: E:\\pcacmgr\\CerFiles\\hjzf_encPublic.cer
  4.  
    encPfxFilePath: E:\\pcacmgr\\CerFiles\\hjzf_encPfx.pfx
  5.  
    encPfxFilePwd:
    11111111

2.通过@Value获取值:

  1.  
    @Configuration
  2.  
    public class PcacIntegrationUtil {
  3.  
    @Value("${pcacmgr.publicCertFilePath}")
  4.  
    private static String publicCertFilePath;
  5.  
     
  6.  
    @Value("${pcacmgr.encPfxFilePath}")
  7.  
    private static String encPfxFilePath;
  8.  
     
  9.  
    @Value("${pcacmgr.encPfxFilePwd}")
  10.  
    private static String encPfxFilePwd;
  11.  
     
  12.  
    @Value("${pcacmgr.encPublicCertFilePath}")
  13.  
    private static String encPublicCertFilePath;
  14.  
     
  15.  
    public static String signData(String sourceData) {
  16.  
    System.out.println(publicCertFilePath);
  17.  
    }
  18.  
    }

3.启动项目调用过程中发现获取值为null。

4.发现是static导致,以下为解决方案:

  1.  
    @Configuration
  2.  
    public class PcacIntegrationUtil {
  3.  
    private static Logger logger = LoggerFactory.getLogger(PcacIntegrationUtil.class);
  4.  
     
  5.  
    private static String publicCertFilePath;
  6.  
    public static String getPublicCertFilePath() {
  7.  
    return publicCertFilePath;
  8.  
    }
  9.  
    @Value("${pcacmgr.publicCertFilePath}")
  10.  
    public void setPublicCertFilePath(String publicCertFilePath) {
  11.  
    PcacIntegrationUtil.publicCertFilePath = publicCertFilePath;
  12.  
    }
  13.  
     
  14.  
    public static String signData(String sourceData) {
  15.  
    System.out.println(publicCertFilePath);
  16.  
    }
  17.  
    }

问题解决,打印结果与yml文件配置的内容相符。

 

心得:使用注解的方式,不过注解写在非static的方法上(Spring的注解不支持静态的变量和方法)。

转载于:https://www.cnblogs.com/lykbk/p/sadfsafef2345234324234.html

你可能感兴趣的文章
[Android] TabLayout设置下划线(Indicator)宽度
查看>>
<潭州教育>-Python学习笔记@条件与循环
查看>>
web自动化之验证码识别解决方案
查看>>
netty接收大文件的方法
查看>>
软件工程设计之四则运算
查看>>
SpringMVC @ResponseBody 406
查看>>
HDOJ---2824 The Euler function[欧拉函数]
查看>>
KMP算法
查看>>
Atlas学习之开始篇[转]
查看>>
第二章 在HTML页面里使用javaScript
查看>>
【Educational Codeforces Round 48 (Rated for Div. 2) D】Vasya And The Matrix
查看>>
正则表达式的性能评测
查看>>
CF1172B Nauuo and Circle
查看>>
CF1178D Prime Graph
查看>>
CF1190D Tokitsukaze and Strange Rectangle
查看>>
CF1202F You Are Given Some Letters...
查看>>
CF1179C Serge and Dining Room
查看>>
CF1168B Good Triple
查看>>
CF1208E Let Them Slide
查看>>
AT2000 Leftmost Ball
查看>>