maven多模块spring bean注入问题

背景及问题

今天在学习有关maven分模块构建工程时,将简单的spring+springmvc+mybatis工程拆分为web模块,service模块,dao模块,以及domain模块。其中service和dao模块有各自的spring配置文件。web模块有对应的spring-mvc配置文件。

完成相应模块的常规代码编写后,访问对应资源,执行控制层代码时遇到报错,无法创建service层的bean实例:
org.springframework.context.support.AbstractApplicationContext.refresh Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘itemController’: Unsatisfied dependency expressed through field ‘itemService’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘cn.yansw.service.ItemService’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

注解使用没有问题,对应的spring配置文件是正确的,组件扫描没有问题。

解决方案

经检查测试,通过修改web模块的web.xml配置中Spring配置文件的路径得以解决:
原路径:classpath:applicationContext*.xml
修改后路径:classpath*:applicationContext*.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    
    <!--指定Spring配置文件位置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>
    
    <!--配置Spring框架启动时使用的监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置SpringMVC的前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--指定springmvc配置文件位置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
    
</web-app>

若classpath后缺少*,则无法跨模块取得对应的spring配置文件。也就造成无法创建bean实例,从而出现报错。

项目结构

  1. domain模块封装从数据库查询得到的实体类
  2. dao模块实现mybatis配置查询数据库
  3. service模块通过调用对应的dao模块完成业务逻辑
  4. web模块包括前端的数据提交、数据展示页面,以及对应的控制层代码

总结与反思

在分模块构建工程时,需要注意是否需要跨模块读取配置文件,在需要的位置classpath后要加*号。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值