java - Spring @Value ("${}") 通常为空

标签 java spring spring-boot spring-bean spring-properties

我正在使用 Spring Boot 应用程序。在某些 @Component 类中,加载了 @Value 字段,而在其他类中,它们始终为 null

似乎 @Value(s) 是在我的 @Bean/@Component 创建后加载的。

我需要从 @Bean 的属性文件中加载一些值。

你有什么建议吗?

最佳答案

属性(以及所有 bean 依赖项)在 bean 构建后(构造函数的执行)注入(inject)。

如果需要,可以使用构造函数注入(inject)。

@Component
public class SomeBean {
    private String prop;
    @Autowired
    public SomeBean(@Value("${some.prop}") String prop) {
        this.prop = prop;
        //use it here
    }
}

另一种选择是将构造函数逻辑移动到使用 @PostConstruct 注释的方法中,它将在创建 bean 并解析它的所有依赖项和属性值后执行。

关于java - Spring @Value ("${}") 通常为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636060/

相关文章:

java - 为什么这个枚举不能编译?

spring - 在 Spring Boot 中使用 Jersey 代替 Spring MVC 来实现 REST API 有什么优势?

java - 转换为 char 数组后 Long 变量出现意外值

java - 如何在应用程序加载时实现默认 Activity ( fragment )。 (抽屉布局)

java - Android Studio 在 ImageView 上显示 Arraylist 的元素

java - 将异常传递给该方法

Spring 分层上下文

java - Spring安全未授权用户

java - Spring Boot + Gradle : take VM options when I run single tests

java - 使用 junit 进行 MQTT 客户端测试