记录一下@Autowired注入为null的情况(补充:根据bean名称从IOC容器中获取bean对象).

场景描述:
自定义的拦截器中需要注入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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卖柴火的小伙子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值