Interceptor拦截器当中注入Service报空指针异常

Interceptor拦截器当中注入Service报空指针异常

 

很多人想当然地直接在拦截器加@Component注解使其成为一个bean对象。这是一种错误的做法。

经过实际测试,确定失败。

 

正确的做法

package com.study.config;

import com.study.interceptor.IdempotencyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Bean
    public IdempotencyInterceptor myInterceptor() {
        return new IdempotencyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor())
                // 拦截的请求
                .addPathPatterns("/**");
        // 不用拦截的请求
        //.excludePathPatterns("/login");
    }
}

 

经过实际的测试

 

 

 

posted @ 2022-03-29 17:41  —阿峰—  阅读(636)  评论(0编辑  收藏  举报