Null pointer problem of spring boot filter injection into Bean

Keywords: Spring xml SpringBoot

   When the doFilterInternal in the filter writes the business code, it needs to use the spring bean component. It is found that the bean component cannot be initialized in the filter, which is NullpointException. After checking, the path of the scan package is OK. Finally, determine the problem caused by the loading order of containers. In web.xml, the execution order of each element is as follows. The context -- > param -- > listener -- > filter -- > servlet can see that the filter has been loaded before the dispatcher servlet of spring MVC is initialized, so null is injected.

The solution is that doFilterInternal uses the spring context to retrieve the corresponding bean components. For Spring Boot, we can use the following steps to solve this problem

Step 1: create the context tool class SpringContextUtil

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;

   
    //Set context
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil .context = applicationContext;
    }

    //Get context
    public static ApplicationContext getApplicationContext(){
        return context; 
    }


    // Get the Bean of the context by name
    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    //Get context bean by type
    public static <T> T setBean(Class<?> requiredType){
        return applicationContext.getBean(requireType);
    }
    

    // International use
    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }

    // Get current environment
    public static String[] getActiveProfiles() {
        return context.getEnvironment().getActiveProfiles();
    }

    // Determine whether the current environment is test/local
    public static boolean isDevEnv(){
        String[] activeProfiles = getActiveProfiles();
        if (activeProfiles.length<1){
            return false;
        }
        for (String activeProfile : activeProfiles) {
            if (StringUtils.equals(activeProfile,"dev")){
                return true;
            }
        }
        return false;
    }
}

Step 2: if you do not inherit ApplicationContextAware, inject applicationContext into the context tool class SpringContextUtil in the main method of the Springboot startup class

 

Step 3: in the corresponding business code, use SpringContextUtil.getBean("xxx") to obtain the corresponding bean components, such as:

 

Posted by Roxie on Sun, 24 Nov 2019 11:30:02 -0800