The problem that the interceptor in springboot cannot inject beans

When using the springboot interceptor, you want to inject beans into the interceptor for easy use, but if you directly inject it, you will find that it cannot be injected and a null pointer exception will be reported, resulting in continuous interception and failure to release.
Solution:
When registering the interceptor, inject the interceptor as a bean

Add @Compant annotation to the interceptor to register as a component

@Configuration
public class InterceptorRegister extends WebMvcConfigurerAdapter {
    
    

    //将拦截器注册为bean,防止无法注入
    @Bean
    public ApiInterceptor apiInterceptor(){
    
    
        return new ApiInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
		//记得这里直接调用apiInterceptor(),得到上面注册的bean      
        registry.addInterceptor(apiInterceptor()).addPathPatterns("/api/**");
        super.addInterceptors(registry);
    }

}

In this way, the problem that the bean cannot be injected into the interceptor can be solved, and the specific principle is not mentioned. After all, everyone is here to solve the problem. I will continue to compile an article if I have time

Guess you like

Origin blog.csdn.net/xiaole060901/article/details/111955953