Home > OS >  Getting Null Value while autowiring Hazelcast instance in springboot in the Interceptor layer but no
Getting Null Value while autowiring Hazelcast instance in springboot in the Interceptor layer but no

Time:02-03

Interceptor class

public class AbcInterceptor implements HandlerInterceptor {

@Autowired
HzMap hzMap;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
           String str = hzMap.get(key); // hzMap is coming as null here 
           return true;

        }

}

Added addInterceptors method in the Configuration class too, annotated with @Configuration.

But the same HzMap is getting autowired in the Filter class without any issue.

@Component public class AbcFilter implements Filter {

@Autowired
HzMap hzMap;

@Override
public void init(FilterConfig filterConfig) throws ServletException {}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                      String str = hzMap.get(key); // hzMap is not null here 
                      filterChain.doFilter(servletRequest, servletResponse);
    }

@Override
public void destroy() {}

}

I tried using the code similar to above i was expecting the HazelcastMap object in the interceptor class.

CodePudding user response:

It looks like the issue is that the HzMap object is not being autowired correctly in the AbcInterceptor class. The autowiring works in the AbcFilter class but not in the AbcInterceptor class.

One possible solution could be to add the @Autowired annotation to the constructor of the AbcInterceptor class instead of the field.

@Autowired
public AbcInterceptor(HzMap hzMap) {
this.hzMap = hzMap;
}

Another solution could be to add the @Component annotation to the HzMap class to make sure that it is a Spring Bean and can be autowired.

CodePudding user response:

This worked for me.

public class AbcInterceptor implements HandlerInterceptor {
    HzMap hzMap;
    public AbcInterceptor(HzMap hzMap) {
        this.hzMap = hzMap;
    }
    rest of the code ....
}

@Configuration
public class AbcConfig implements WebMvcConfigurer {

@Autowired
HzMap hz;

@Override
public void addInterceptors(InterceptorRegistry registry){
    registry.addInterceptor(new AbcInterceptor(hz)).addPathPatterns("/**");
}
}
  • Related