SSM监听器无法自动注入service,解决方案

此博客记录自己的学习过程

在ssm框架web开发中,可以采用监听器来初始化页面信息,服务器启动时启动,但是监听器中无法自动注入service,需要采用其他方式如下

初始化页面信息采用application对象
在这里插入图片描述

package com.ssm.web.filter;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ssm.common.bean.Book;
import com.ssm.common.bean.Category;
import com.ssm.common.util.LogImpl;
import com.ssm.common.util.interfaces.Log;
import com.ssm.service.serviceImpl.BookServiceImpl;
import com.ssm.service.serviceImpl.CategoryServiceImpl;

/**
 * Application Lifecycle Listener implementation class ApplicationListener
 *监听器
 */
@WebListener
public class ApplicationListener implements ServletContextListener {
	private Log log = new LogImpl();
    /**
     * Default constructor. 
     */
    public ApplicationListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     * 服务器启动时启动,初始化页面信息
     */
   
    public void contextInitialized(ServletContextEvent arg0)  { 
   
    	//获取service层对象,无法采用自动注入,采用WebApplicationContextUtils
    	BookServiceImpl bookServiceImpl = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getBean(BookServiceImpl.class);
    	CategoryServiceImpl categoryServiceImpl=WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getBean(CategoryServiceImpl.class);
    	
    	
    	log.info("监听器初始化运行");
    	
    	List<Book> list = bookServiceImpl.findAllBooks();
    	List<Category> list2 = categoryServiceImpl.findAllCategory();
    	ServletContext application = arg0.getServletContext();
    	log.info("页面初始化完成");
    	application.setAttribute("categorys", list2);
    	application.setAttribute("books",list);

    }
	
}

在web.xml中加上监听地址

 <listener>
    <listener-class>com.ssm.web.filter.ApplicationListener</listener-class>
  </listener>

至此页面初始化成功

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值