【发布时间】:2020-10-06 03:51:20
【问题描述】:
我正在使用
@Service
public class Foo
{
@Value ("${this.does.not.exist: 10}")
private static int bar;
}
因为配置中不存在该值,所以我期望bar 具有值10,但它是0。
我也按照this answer尝试了@Value ("${this.does.not.exist: #{10}}"),它仍然是零。
为什么这不起作用?
【问题讨论】:
-
代码看起来很好,对我来说也很好。
#{10}也应该不需要。您正在使用哪些依赖项(例如 Spring 版本)? -
你是如何使用
Foo类的 - 作为 Spring bean 的?如果您自己创建new Foo(),这将不起作用(然后bar将具有其默认值0)。 Spring 只会在 Spring bean 中解析@Value。 -
@Jesper 我在
@Configuration class ... extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService () {return new Foo ();}中使用它我应该如何构建它? -
@spraff 这不起作用。您总是必须自动装配 bean,以便它们由 Spring 创建。由于您已经在使用@Service,bean 会自动实例化,并且可以通过
@Autowired Foo foo;(或@Autowired UserDetailsService foo,因为您似乎 UserDetailsService == Foo)使用
标签: spring spring-boot