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°角仰望天空....)

          

 

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

 

 

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值