2017-09-14 136 views
1

INT激活和int ForgotPassword的作品不錯,但字符串變量返回null我需要的AppSettings靜態類@PropertySource @Value靜態字符串返回null

@PropertySource("classpath:appSettings.properties") 
    public class AppSettings { 

     @Value("${Activation}") 
     private static int Activation; 
     @Value("${ForgotPassword}") 
     private static int ForgotPassword; 
     @Value("${CryptoSplit}") 
     private static String CryptoSplit; 
     @Value("${CryptoKey}") 
     private static String CryptoKey; 

     public static String getCryptoSplit() { 
      return CryptoSplit; 
     } 

     public static String getCryptoKey() { 
      return CryptoKey; 
     } 
     public static int getActivation() { 
      return Activation; 
     } 

     public static int getForgotPassword() { 
      return ForgotPassword; 
     } 

    } 

的.properties

Activation=0 
ForgotPassword=1 
CryptoSplit=:OSK: 
CryptoKey=TheBestSecretKey 
+1

寫setter方法,把'@ Value'上setter方法,而不是放置變量 – pvpkiran

+1

您不能在'static'字段/方法上自動連線或使用'@ Value'。 –

+0

如果你想使用值註釋定義一個靜態變量請看[這個答案](https://stackoverflow.com/a/45192557/3493036) – Patrick

回答

0

Spring does not suppor t @Value注射靜態字段。

你確定你肯定需要「靜態類的AppSettings」?我懷疑這可能是對Spring單身人士工作方式的誤解。

但是,如果你有一個「對的AppSettings靜態類」,那麼你可以實現這個如下真正需求:

@Value("${CryptoKey}") 
public void setCryptoKey(String cryptoKey) { 
    AppSettings.CryptoKey = CryptoKey; 
} 
0

@Value()獲取調用該bean的初始化,該bean在啓動時不需要初始化,所以除非該bean初始化,否則不會有該值。