0

Does @Value field injection require to be under a @RestController / @Configuration class for it to work?

I went through countless tutorials no one seem to mention anything like it, but wen I tried on my own code it just doesn't work. I found suppose solution here: Spring Boot application.properties value not populating But it didn't work in my case.

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

  @Value("${token.secret}")
  private String tokenSecret;   <--- always null
  @Value("${token.expiration_time}")
  private String tokenTime;     <--- always null
  
  ...

  @PostConstruct  <-- this was suggested but still null
  public void init(){
      log.info("tokenTime : {}", tokenTime);
      log.info("tokenSecret: {}", tokenSecret);
 }
}

I then moved these fields to my @Configuration or @RestController class the values does get populated, why is that? and how to fix this in my AuthenticationFilter?

@Configuration
@EnableWebSecurity
public class AppWebSecurity extends WebSecurityConfigurerAdapter {

  @Value("${token.secret}")
  private String tokenSecret;
  @Value("${token.expiration_time}")
  private String tokenTime;
  ....
}

Thank you

Eric Huang
  • 1,114
  • 3
  • 22
  • 43
  • 3
    It works for any Spring managed bean. If they aren't passed the bean isn't spring managd. As it is a security related class you probably do somthing like `addFilter(new AuthenticationFilter())` basically creating an instance outside of the scope of spring (not spring managed) and as such won't get those values replaced. – M. Deinum Oct 27 '22 at 18:07
  • ohhh okey, thanks. Thanks for clarifying this, this was not specify in the docs. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html. You want to put your comments in to answer? I will mark it after. – Eric Huang Oct 28 '22 at 07:58

0 Answers0