监听器(listener)和过滤器(fitter)@Autowired无法注入bean解决方法

ApplicationContext :

是Spring中的核心接口和容器,允许容器通过应用程序上下文环境创建、获取、管理bean。在构建容器的时候,创建对象采用的策略是立即加载的方式,即只要一读取完配置文件就立即创建配置文件中配置的对象。

BeanFactory:

采用的是延迟加载的方式,什么时候根据id获取对象了,什么时候才真正地创建对象。

/**
 * @author yt
 * @create 2022/10/27 16:50
 */
public class StudentListener extends AnalysisEventListener<StudentRead> {
    
    //错误的示范,直接使用@Autowired进行注入
    @Autowired
    private StudentReadMapper studentReadMapper ;

错误:使用@Autowired注入service对象,最终得到的为null;

原因:监听器(listener)、过滤器(fitter)都不是Spring容器管理的,无法在这些类中直接使用Spring注解的方式来注入我们需要的对象。

解决:写一个bean工厂,从spring的上下文WebApplicationContext 中获取。

这里记录一下 ApplicationContext 的使用方法,创建工具类

package com.example.demo.listener;

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

/**
 * @ClassName: MyApplicationContext
 */
@Component
public class MyApplicationContext implements ApplicationContextAware {


    private static ApplicationContext applicationContext;

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

    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        if (applicationContext == null) {
            return null;
        }
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> name) throws BeansException {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(name);
    }
}

然后将直接在里面获取即可

public class StudentListener extends AnalysisEventListener<StudentRead> {

    private StudentReadMapper studentReadMapper = MyApplicationContext.getBean(StudentReadMapper.class);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值