【问题标题】:Spring boot `@Value` is always zero, despite default尽管默认值,Spring boot `@Value` 始终为零
【发布时间】: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,因为您似乎 UserDetailsS​​ervice == Foo)使用
  • 这能回答你的问题吗? Why can't we autowire static fields in spring?

标签: spring spring-boot


【解决方案1】:

我在 OP(现已编辑)中省略了 static 关键字,这是错误所在。

【讨论】:

    【解决方案2】:

    以下代码适用于我:

    @Service
    public class MyService {
        @Value("${this.does.not.exist: 10}")
        private int val;
    

    使用最新版本的 spring-boot(基本上应该使用任何其他版本)。

    所以问题一定出在其他地方。

    请检查以下内容:

    • 确保Foo确实由spring管理(在组件扫描过程中找到)。否则没有人会注入价值。

    • 确保您没有尝试从构造函数或其他内容中读取值: 在春季,它首先创建对象(此时该字段的值确实为 0),然后才触发 bean 后处理器以注入值、自动装配等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-12
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多