LMLPHP后院

解决 springboot Interceptor @Autowired null技术

maybe yes 发表于 2017-09-13 17:25

看如下代码块:

package com.lmlphp.nb.config;

import com.lmlphp.nb.interceptor.WebInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebInterceptor())
                .addPathPatterns("/*")
                .excludePathPatterns("/login");
        super.addInterceptors(registry);
    }

}

上面的代码看似非常简洁,其实是有一些问题的。当 WebInterceptor 类中使用了 @Autowired 的属性就会出现空指针错误问题原因:拦截器加载时间点在 springcontext 之前,所以在拦截器中注入值为 null,使用 Bean 注解提前加载即可解决。代码改成如下:

@Bean
public HandlerInterceptor getWebInterceptor(){
    return new WebInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(getWebInterceptor())
            .addPathPatterns("/*")
            .excludePathPatterns("/login");
    super.addInterceptors(registry);
}

咋一看,特别繁琐啊,new 一个对象还得封装成一个方法,这个是初学者所容易忽略的。

2024-04-25 14:32:42 1714026762 0.028737