【问题标题】:@PropertySource @Value static strings return null [duplicate]@PropertySource @Value 静态字符串返回 null [重复]
【发布时间】:2017-09-14 12:23:57
【问题描述】:

int Activation 和 int ForgotPassword 效果很好,但字符串变量返回 null 我需要 AppSettings 的静态类

@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;
        }

    }

.属性

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

【问题讨论】:

  • 编写setter方法并将@Value放在setter方法上,而不是放在变量上
  • 您不能在static 字段/方法上自动连接或使用@Value
  • 如果您想使用值注释定义静态变量,请查看this answer

标签: java spring spring-boot properties appsettings


【解决方案1】:

Spring 不支持 static 字段上的@Value 注入。

您确定确实需要“AppSettings 的静态类”吗?我怀疑这可能代表对 Spring 单例如何工作的误解。

但是,如果您确实需要“AppSettings 的静态类”,那么您可以按如下方式实现:

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

【讨论】:

    【解决方案2】:

    @Value() 在 bean 的初始化时被调用,bean 不需要在启动时被初始化,所以除非 bean 被初始化,否则你将没有值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 2014-11-21
      相关资源
      最近更新 更多