在一次SSM项目中要使用到全局变量,想到了使用监听器进行全局配置。
1、在javaweb项目中,我们的项目启动时会不避免的进行一些初始化操作,这些初始化操作也是对数据库进行操作的,故我们需要读取数据库配置文件。
代码如下:
@WebListener
public class ApplicationListener implements ServletContextListener {
@Autowired
private CategoryService categoryService;
@Autowired
private BookService bookService;
//初始化执行
public void contextInitialized(ServletContextEvent sce) {
//获取所有类型
List<Category> categories = categoryService.allType();
//获取所有书籍
List<Book> books = bookService.allBook();
sce.getServletContext().setAttribute("books",books);
sce.getServletContext().setAttribute("categories",categories);
}
//结束页面执行
public void contextDestroyed(ServletContextEvent sce) {
}
2、运行过后报错空指针异常:
3、监听器需要配置web.xml文件,但是配置过后还是此错误,所以此方法无效。
4、报错原因:
当servlet容器初始化完成后便会调用contextInitialized方法。但是通常我们在执行初始化的过程中会调用service和dao层提供的方法,而现在web项目通常会采用spring框架来管理和装配bean。
生命周期不同:
Listener的生命周期和spring管理的bean的生命周期:
(1)Listener的生命周期是由servlet容器(例如tomcat)管理的,项目启动时上例中的ApplicationListener是由servlet容器实例化并调用其contextInitialized方法,而servlet容器并不认得@Autowired注解,因此导致categoryService和bookService实例注入失败。
(2)而spring容器中的bean的生命周期是由spring容器管理的。
5、那么该如何在spring容器外面获取到spring容器bean实例的引用呢?
再此之前我看过很多方法,但是都是不成功。最后想到此类方法:
在监听器中手动加载spring的配置文件和spring所管理的bean:
@WebListener
public class ApplicationListener implements ServletContextListener {
//初始化执行
public void contextInitialized(ServletContextEvent sce) {
//加载spring的主配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean,这个bean就是service,SSM进行注册实体类实现service bean时所配的id名
CategoryService categoryService = context.getBean("categoryService", CategoryService.class);
BookService bookService = context.getBean("bookService", BookService.class);
//查询所有的类型
List<Category> categories = categoryService.allType();
//查询所有的书籍
List<Book> books = bookService.allBook();
//放入全局变量application
ServletContext application = sce.getServletContext();
application.setAttribute("books",books);
application.setAttribute("categories",categories);
//System.out.println(books);
}
//结束页面执行
public void contextDestroyed(ServletContextEvent sce) {
}
6、使用此方法可以成功执行并且获取到所需要的全局数据。
7、此监听类是一个实体类,不要在配置文件中忘记注册此类啊。
<!--监听器-->
<bean class="com.chen.listener.ApplicationListener"/>
8、前路漫漫、