SpringBoot使用@Value從yml文件取值爲空--注入靜態變量
1.application.yml中配置內容以下:html
-
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獲取值:app
-
@Configuration
-
public class PcacIntegrationUtil {
-
@Value("${pcacmgr.publicCertFilePath}")
-
private static String publicCertFilePath;
-
-
@Value("${pcacmgr.encPfxFilePath}")
-
private static String encPfxFilePath;
-
-
@Value("${pcacmgr.encPfxFilePwd}")
-
private static String encPfxFilePwd;
-
-
@Value("${pcacmgr.encPublicCertFilePath}")
-
private static String encPublicCertFilePath;
-
-
public static String signData(String sourceData) {
-
System.out.println(publicCertFilePath);
-
}
-
}
3.啓動項目調用過程當中發現獲取值爲null。spa
4.發現是static致使,如下爲解決方案:code
-
@Configuration
-
public class PcacIntegrationUtil {
-
private static Logger logger = LoggerFactory.getLogger(PcacIntegrationUtil.class);
-
-
private static String publicCertFilePath;
-
public static String getPublicCertFilePath() {
-
return publicCertFilePath;
-
}
-
@Value("${pcacmgr.publicCertFilePath}")
-
public void setPublicCertFilePath(String publicCertFilePath) {
-
PcacIntegrationUtil.publicCertFilePath = publicCertFilePath;
-
}
-
-
public static String signData(String sourceData) {
-
System.out.println(publicCertFilePath);
-
}
-
}
問題解決,打印結果與yml文件配置的內容相符。htm
心得:使用註解的方式,不過註解寫在非static的方法上(Spring的註解不支持靜態的變量和方法)。get