工件SSM:war exploded: 部署工件时出错。请参阅服务器日志了解详细信息

今天往web.xml中添加一个Listener监听器就出现了异常

Tomcat服务器启动时工件部署失败

查看日志得知是没有注入引用dao层的bean:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'ProductTypeService' available

这个时候就要检查自己相关的bean注入是否完成了,查看代码时发现的确是缺少了一个bean注入:

手动添加了bean注入:

以为这个时候就能识别到了吧,但出人意料的是依旧报相同的错误!


仔细想一下,查看我监听器的代码,监听器实现了ServletContextListener接口,是一个全局监听器,也就是项目刚启动是就会生效,于是我添加了一条输出信息,就是“进入监听器”

import com.konan.pojo.ProductType;
import com.konan.service.ProductTypeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

public class ProductTypeListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("进入监听器");
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext_*.xml");
        ProductTypeService productTypeService = (ProductTypeService) context.getBean("ProductTypeService");
        List<ProductType> allType = productTypeService.getAllType();
        System.out.println(allType);

        sce.getServletContext().setAttribute("typeList",allType);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

重启查看控制台:

 可以看到监听器是在部署工件后就生效了,但是此时工件还没有部署好!

之后便报除了相同的错误

这时候为什么还识别不到 ProductTypeService 这个注入的bean呢?明明已经注入了呀!


监听器中要获得的是 ProductTypeService 业务层的这个bean,也就是ProductTypeServiceImpl的上层接口。由于监听器过早的生效时间导致我们自动注入的bean的引用名称还没有生效(实际上bean已经注入了,但是监听器此时识别不到,小写类名首字母也没有用),这时候就要用到自定义bean名称了!

添加@Service("bean") 

  • 自定义bean名称,可以@Service(“aaaaa”)这样来指定,这种bean默认是单例的
  • 不指定时的默认名称是类名(头字母小写),

最终修改为如下形式即可正常运行!

猜你喜欢

转载自blog.csdn.net/m0_57538148/article/details/123965591
今日推荐