工件SSMwar 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默认是单例的
  • 不指定时的默认名称是类名(头字母小写),

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

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

猜你喜欢

转载自blog.csdn.net/web18334137065/article/details/126081168