1

I am using

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

Because the value does not exist in the configuration, I was expecting bar to have value 10 but it is 0.

I also tried @Value ("${this.does.not.exist: #{10}}") as per this answer, it's still zero.

Why didn't this work?

spraff
  • 32,570
  • 22
  • 121
  • 229
  • 1
    The code looks fine and works fine for me. `#{10}` should also not be needed. Which dependencies (e.g. Spring versions) are you using? – jAC Jun 16 '20 at 14:03
  • How are you using class `Foo` - as a Spring bean? This will not work if you create a `new Foo()` yourself (then `bar` will have its default value `0`). Spring will only resolve `@Value` in Spring beans. – Jesper Jun 16 '20 at 14:05
  • @Jesper I am using it within `@Configuration class ... extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService () {return new Foo ();}` how should I structure this? – spraff Jun 16 '20 at 14:17
  • 1
    @spraff This doesn't work. You always have to autowire beans so they're created by Spring. Since you're already using @Service, the bean is automatically instantiated and can be used via `@Autowired Foo foo;` (or `@Autowired UserDetailsService foo` since it seems that you UserDetailsService == Foo) – jAC Jun 16 '20 at 14:18
  • Does this answer your question? [Why can't we autowire static fields in spring?](https://stackoverflow.com/questions/10938529/why-cant-we-autowire-static-fields-in-spring) – jAC Jun 17 '20 at 07:13

2 Answers2

1

I omitted the static keyword in the OP (now edited) and that was the fault.

spraff
  • 32,570
  • 22
  • 121
  • 229
0

The following code works for me:

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

With the last version of spring-boot (and it should with any other version basically).

So the issue must be elsewhere.

Please check the following:

  • Make sure that Foo is indeed managed by spring (it finds it in the component scanning process). Otherwise no-one will inject the value.

  • Make sure that you're not trying to read the value from constructor or something: In spring it first creates the object (and at that moment the value of the field is 0 indeed) and only then triggers a bean post processors for injecting values, autowiring, etc.

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97