浅谈application-*.xml和springmvc-.xml的区别

本文探讨了Spring MVC与Spring框架整合时常见的配置问题及解决方法。通过对比application-*.xml与springmvc-*.xml的配置策略,分析了<context:component-scan/>与<mvc:annotation-driven>注解的使用顺序及其对Bean注入的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.项目配置说明

 一般springMVC和Spring的整合过程中,我们喜欢配置两个文件application-*.xml和springmvc-.xml,但是配置不好的话,很容易出现这样的问题:Injection of resource dependencies failed; nested exception is org.springfra…,也就是注入bean失败的问题。

 一般对文件的配置喜欢<context:component-scan base-package=“com.edu”/>这样的话,可以扫描整个包下面的文件,但是也会导致效率的问题,因为是扫描这个包下面所有的controller、service和bean等。另外一种方法是,扫描的具体的包,一个一个配置,但是这样有很繁琐。

所以我们会采用这样的配置:

<context:component-scan base-package="com.edu" >
     <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

 利用use-default-filters和context:include-filter属性来进行区别,这样的话就可以根据自己的需要来扫描那个层,是controller还是service层。但是这样话,有些类就可能注入不进来,导致出现这样的问题:Injection of resource dependencies failed; nested exception is org.springfra…

2.解决方案

  因为上面的问题,所以我们需要对区别application-.xml和springmvc-.xml很是了解。一般我喜欢把controller层springmvc-.xml文件中,service层配置在application-.xml中。

 所以springmvc-.xml也是处理controller层相关的注解,而application-*.xml一般配置其他,比如出c3po0等。但是也会导致出现:Injection of resource dependencies failed; nested exception is org.springfra…,所以一般情况下我会把<mvc:annotation-driven ></mvc:annotation>等注解配置在 <context:component-scan />的前面,因为 <context:component-scan /> ,会自动注入@controller等注解。这又涉及到<mvc:annotation-driven >和<context:component-scan />他们两个注解之间的区别。

 第二个区别就是application-.xml和springmvc-.xml的加载顺序是不一样的,所以一定分清楚,那些要先加载的,应该放在application-.xml中。因为这涉及到web.xml的加载顺序问题。application-.xml配置在下,而springmvc-*.xml配置在servlet下面。根据web.xml的加载顺序是:context-param -> listener -> filter -> servlet。也可以说是按照加载顺序来配置文件的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值