java - @PropertySource @Value 静态字符串返回 null

标签 java spring spring-boot properties appsettings

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

最佳答案

Spring 不支持在静态字段上注入(inject)@Value

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

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

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

关于java - @PropertySource @Value 静态字符串返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46219065/

相关文章:

java - 递归拼出一个词

java - 如何使用 Java Regex 将特定字符串放入数组?

spring - 使用 Spring mvc 创建第一个 Hello world 应用程序时出错

spring-boot - 应用程序无法使用 Spring Boot RC2 启动

java - 多态性如何用于内部类?

java - 刷新了 Spring Boot 上下文中的 Jooq CastException

java - 如何通过maven导入多个Spring应用程序,其中每个依赖项位于自己的类路径上(以避免依赖项冲突)?

java - spring boot 将 jsp 加载为 txt?

spring - 无法在 Spring Boot 启动时执行 data.sql 和 schema.sql

java - session#refresh 不使用@ManyToOne 和复合键刷新根实体