【视频 & 交流平台】
http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share
http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share
https://gitee.com/happyangellxq520/spring-boot
http://412887952-qq-com.iteye.com/blog/2321532
需求缘起:
在研究《Spring Boot集成Quartz升级篇》的时候,用到了AutowireCapableBeanFactory,什么情况下用到了呢?我们知道在Quartz具体执行任务的代码在Job类当中(具体是实现了Job的类),如果我们在Job类使用@Autorire注入的类话,那么是会报NullPointerException的。好了,这节文章介绍下如何使用AutowireCapableBeanFactory。
本章大纲:
(2)AutowireCapableBeanFactory的作用
(3)例子
接下里看下本节具体的内容:
(1)问题的抛出
在应用中一般普通的JavaPojo都是由Spring来管理的,所以使用autowire注解来进行注入不会产生问题,但是有两个东西是例外的,一个是 Filter,一个是Servlet,这两样东西都是由Servlet容器来维护管理的,所以如果想和其他的Bean一样使用Autowire来注入的 话,是需要做一些额外的功夫的。
(2)AutowireCapableBeanFactory的作用
让不受spring管理的类具有spring自动注入的特性
(3)例子
在spring boot 使用过程中可能会需要自定义个servletContextListener 并有可能需要注入spring管理的类,这时候如果没有特殊的配置的话,可能就会注入失败,这是网上很多碰到的问题,在这里博主要说明在1.4.0+版本,是不会出现这个问题的。这里只是为了讲解,那这个通俗易懂的案例来讲解而已:
package com.kfit.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.kfit.service.HelloService;
@WebListener
public class MyServletContextListener implements ServletContextListener {
@Autowired
private HelloService helloService;
@Override
public void contextDestroyed(ServletContextEvent event) {
}
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("MyServletContextListener.contextInitialized()");
AutowireCapableBeanFactory autowireCapableBeanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext()).getAutowireCapableBeanFactory();
autowireCapableBeanFactory.autowireBean(this);
}
}
视频&交流平台:
http://study.163.com/course/introduction.htm?courseId=1004329008
http://412887952-qq-com.iteye.com/blog/2321532