SpringBoot使用@Value從yml檔案取值為空--注入靜態變數
阿新 • • 發佈:2018-12-24
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的註解不支援靜態的變數和方法)。