Spring @Value(" $ {}")通常为null [英] Spring @Value("${}") often null

查看:266
本文介绍了Spring @Value(" $ {}")通常为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Spring Boot application. In some @Component class @Value fields are loaded, instead on other classes they are always null.

似乎 @Value (s)在我的<$之后加载c $ c> @Bean / @Component 已创建。

Seems that @Value(s) are loaded after my @Bean/@Component are created.

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

I need to load some values from a properties file in my @Bean.

您有什么建议吗?

推荐答案

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

The properties(and all of the bean dependencies) are injected after the bean is constructed(the execution of the constructor).

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

You can use constructor injection if you need them there.

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

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

Another option is to move the constructor logic in method annotated with @PostConstruct it will be executed after the bean is created and all it's dependencies and property values are resolved.

这篇关于Spring @Value(&quot; $ {}&quot;)通常为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆