场景描述:
自定义的拦截器中需要注入userService,但是调试的时候发现可以注入userService,但是显是null.原因就是自定义的拦截器是new出来的,不会被spring容器管理,所以注入userService就会失败.下面贴一下自己的代码:
修改一下配置类中获取拦截器的方式:
补充:根据对象名从spring容器中获取对象
封装工具类:
/**
* @ClassName: StringUtils
* @Desc: spring工具类
* @Author: txm
* @Date: 2021/3/1 13:30
**/
@Component
public class StringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(StringUtils.applicationContext == null){
StringUtils.applicationContext=applicationContext;
}
}
// 获取所有的bean对象
public String[] getAllSpringBean(){
String[] beanNamesForType = StringUtils.applicationContext.getBeanNamesForType(Object.class);
return beanNamesForType;
}
// 根据bean名称获取bean对象
public Object getSpringBean(String beanName){
Object bean = StringUtils.applicationContext.getBean(beanName);
return bean;
}
}
测试类中测试代码:
@Autowired
private StringUtils stringUtils;
@Test
public void testSpringBoot(){
// 获取所有的bean对象
String[] allSpringBean = stringUtils.getAllSpringBean();
System.out.println(allSpringBean);
// 根据bean名称获取bean对象
GoodsController goodsController =(GoodsController) stringUtils.getSpringBean("goodsController");
System.out.println(goodsController);
}