springboot 拦截器intecpter中不能注入bean的解决方案

显而易见,拦截器的执行是在bean的初始化之前,所以如果在代码中直接写上如下图所示

 

因为UserService初始化在拦截器之后.

所以要在拦截器中直接注入 现在探索出两种方式

第一种 在拦截器配置文件中注入UserService 把userService作为参数传递进拦截器的注册方法里 如下:

@Configuration
public class WebAppConfig extends WebMvcConfigurationSupport {

    @Autowired
    private UserService userService;
    @Bean
    public AuthenticationInterceptor authenticationInterceptor(UserService userService) {
        return new AuthenticationInterceptor(userService);
    }

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

注入成功.

只不过webAppConfig中在编译的时候 系统会提示userService为空.

第二种:

SpringContextinterceptorAdapter()实现了ApplicationContextAware的接口

ApplicationContextAware的工具类,可以通过其它类引用它以操作spring容器及其中的Bean实例。

具体代码:

package fzm.tcm.security.annotation;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

第三种来源于百度 度娘首条说 在配置文件中把

@Autowire
public AuthenticationInterceptor authenticationInterceptor() {
    return new AuthenticationInterceptor();
}

@Autowire注解换成@Bean注解有奇效 没看出来.... 反正我没实现出来  可能我的代码这种方法实现不了吧

(45°角仰望天空....)

          

                                                                                                                                 以上 随便转载 不要暴露我秃头的蹦迪身份就好

 

猜你喜欢

转载自blog.csdn.net/qq_31310291/article/details/84579381
今日推荐