java Spring @Value("${}") 经常为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28636060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring @Value("${}") often null
提问by drenda
I'm using Spring Boot application. In some @Component
class @Value
fields are loaded, instead on other classes they are always null
.
我正在使用 Spring Boot 应用程序。在某些@Component
类中,@Value
字段被加载,而在其他类中,它们总是null
.
Seems that @Value
(s) are loaded after my @Bean
/@Component
are created.
似乎@Value
(s) 在创建我的@Bean
/之后加载@Component
。
I need to load some values from a properties file in my @Bean
.
我需要从我的@Bean
.
Have you some suggestion?
你有什么建议吗?
回答by Evgeni Dimitrov
The properties(and all of the bean dependencies) are injected after the bean is constructed(the execution of the constructor).
属性(以及所有的 bean 依赖项)在 bean 被构造(构造函数的执行)之后被注入。
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
}
}
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.
另一种选择是将构造函数逻辑移动到带有注释的方法中,@PostConstruct
它将在创建 bean 并解析它的所有依赖项和属性值后执行。
回答by Efe Kahraman
Have you tried:
你有没有尝试过:
@Component
@PropertySource("file:/your/file/path")
public class MyBean {
private @Value("${property}") String property;
...
}
回答by mahesh chakravarthi
It can happen when you are resolving it into a static variable. I had observed this sometime back and resolved it just by removing static. As people always say, exercise caution while using static.
当您将其解析为静态变量时,可能会发生这种情况。我曾经观察过这个问题,并通过消除静电来解决它。正如人们常说的,使用静电时要小心。
回答by ghxin
Another possible reason is that the '@Value' lines are below the lines that need these properties/values.
另一个可能的原因是“@Value”行低于需要这些属性/值的行。
I spent a lot of time debugging this problem, and found out that the order of lines matters!
我花了很多时间调试这个问题,发现行的顺序很重要!