1.工具类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @Author ***
* @Date 2022/1/8 16:25
* @Version 1.0
* @remark 系统未加载bean时获取bean
*/
@Component
public class SpringBeanFactoryUtils implements ApplicationContextAware {
private static ApplicationContext context = null;
//获取bean
public static <T> T getBean(Class<T> type) {
return context.getBean(type);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringBeanFactoryUtils.context == null) {
SpringBeanFactoryUtils.context = applicationContext;
}
}
}
2.使用
//手动获取Bean对象
redisTemplate = SpringBeanFactoryUtils.getBean(StringRedisTemplate.class);
3.单页面使用
如果你只需要使用一次,可用如下方法
public <T> T getBean(Class<T> clazz, HttpServletRequest request) {
WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
return applicationContext.getBean(clazz);
}
调用的时候:
UserMapper userMapper = getBean(UserMapper.class, request);
4.无法自动注入的原因
我看了很多篇大神的文章,说的都是spring注入的顺序,servlet再过滤器拦截器后面,所以注入不进去,那就要从上下文中获取。