2017-09-14 129 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初始化,否则不会有该值。