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);