首页 > 解决方案 > 为什么我不能访问带有 @SpringBootApplication 注释的主文件之外的 application.properties 值?

问题描述

我的 Spring Bootapplication.properties文件中有一个自定义的键值对:

jwt.secret=secretkey

我在与运行器类相同的目录中为此属性创建了一个配置类:

@Configuration
@ConfigurationProperties(prefix = "jwt")
@PropertySource("classpath:application.properties")
public class JwtProperties {

    /**
     * Secret key used to sign JSON Web Tokens
     */
    private String secret = "";

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }
}

正如预期的那样,我可以ServerApplication.java使用@Value注释在我的主 Spring runner 类中访问这个值:

@SpringBootApplication
@EnableConfigurationProperties(JwtProperties.class)
public class ServerApplication implements CommandLineRunner {

    @Value("${jwt.secret}")
    String test;

    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        // correctly prints "test is: secretkey"
        System.out.println("test is " + test);
    }
}

我有一个类/security/JwtClient.java,我希望能够使用这个jwt.secret属性,但我无法让@Value注释工作(它总是产生一个null字符串):

@Component
public class JwtClient {

    @Value("${jwt.secret}")
    private String secretKey;

    public String buildJWT(Customer customer) {
        // incorrectly prints "secret key: null"
        System.out.println("secret key: " + secretKey);

        // attempts to build JSON Web Token here but secret key is missing
    }

}

我已经阅读了许多有关此主题的 StackOverflow 问题,但几乎所有问题似乎都认为@Value注释将在@Component-annotated 类上正常工作。我在这里想念什么?

标签: javaspringspring-boot

解决方案


推荐阅读