Home > Software design >  accessing @Value inside custom spring boot filter
accessing @Value inside custom spring boot filter

Time:12-20

I have a spring boot filter mentioned below. I want to access a properties.file value in this filter. @Value seems to be not giving null value. I have seen previous answers where they have mentioned that filter is not part of spring boot context that is why @Value annotated field is not readable. But I am not able to find a correct implementation that how can access @Value inside filter.

@Component
public class SecurityAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

        // custom logic

        filterChain.doFilter(request, response);
    }
}

CodePudding user response:

In theory , there should not be any differences to inject the value from the properties file as long as they are defined as spring bean.

So assuming that your SecurityAuthenticationFilter can be successfully registered as a spring bean, the properties can be injected into it by :

@Component
public class SecurityAuthenticationFilter extends OncePerRequestFilter {

    @Value("${foobar.config1}")
    private String config1;
    
    @Value("${foobar.config2}")
    private String config2;
  

}

If it does not work in your case , it is more related to other configuration problem rather than @Value , which you need to provide me more information to figure out why it does not work.

CodePudding user response:

You can solve this by 2 ways:

  • Create bean that will store your data from properies file (pretty good when you have lot of properties):
@Configuration
@ConfigurationProperties(prefix = "prefix")
public class ConfigProperties {
    
    private String val1;
    private int val2;
    private String val3;

    // standard getters and setters
}

this will read properties like: prefix.val1, prefix.val2 and prefix.val3 note that setters are mandatory (to incject values) this object may be incjeted to any component, to get values from this simply use getters

  • Inject values as class values like:
@Component
public class SecurityAuthenticationFilter extends OncePerRequestFilter {

    @Value("${prefix.val1}")
    private String val1;

    @Value("${prefix.val2}")
    private String val2;

    @Value("${prefix.val3}")
    private String val3;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

        doSomething(val1, val2);

        filterChain.doFilter(request, response);
    }
}
  • Related