SpringBoot使用@Value从yml文件取值为空--注入静态变量
1.application.yml中配置内容如下:
- pcacmgr:
- publicCertFilePath: E:\\pcacmgr\\CerFiles\\xh_public.cer
- encPublicCertFilePath: E:\\pcacmgr\\CerFiles\\hjzf_encPublic.cer
- encPfxFilePath: E:\\pcacmgr\\CerFiles\\hjzf_encPfx.pfx
- encPfxFilePwd: 11111111
2.通过@Value获取值:
-
- public class PcacIntegrationUtil {
-
- private static String publicCertFilePath;
-
-
- private static String encPfxFilePath;
-
-
- private static String encPfxFilePwd;
-
-
- private static String encPublicCertFilePath;
-
- public static String signData(String sourceData) {
- System.out.println(publicCertFilePath);
- }
- }
3.启动项目调用过程中发现获取值为null。
4.发现是static导致,以下为解决方案:
-
- public class PcacIntegrationUtil {
- private static Logger logger = LoggerFactory.getLogger(PcacIntegrationUtil.class);
-
- private static String publicCertFilePath;
- public static String getPublicCertFilePath() {
- return publicCertFilePath;
- }
-
- public void setPublicCertFilePath(String publicCertFilePath) {
- PcacIntegrationUtil.publicCertFilePath = publicCertFilePath;
- }
-
- public static String signData(String sourceData) {
- System.out.println(publicCertFilePath);
- }
- }
问题解决,打印结果与yml文件配置的内容相符。
心得:使用注解的方式,不过注解写在非static的方法上(Spring的注解不支持静态的变量和方法)。