3

在我的 Spring MVC web 应用程序中,我想将基于 xml 的配置与注释混合:我使用 , 等注释@Controller@RequestMapping("bla.htm")s@RequestParam解析HttpRequestController方法。因此我添加了

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<context:component-scan base-package="somePackage.controller"/>

到我的dispatcher-servlet.xml.

但是我的控制器有属性。这些属性可以通过@AutoWired注释注入。但我也确实定义了范围。所以我每个属性都有两个注释,这使得代码可读性差。所以我想在我的applicationContext.xml文件中注入依赖项。

有没有办法可以保留注释驱动的请求映射,但使用 context.xml 文件进行依赖注入?还是只能使用注释或 xml 配置?

注意:我用于依赖注入的 bean 位于不同的 xml 文件中。

PS:

我应该提到,我使用 Spring 2.5 并且无法升级它。

4

2 回答 2

4

不,<mvc:annotation-driven>适用于 XML。但是你需要摆脱<context:component-scan>.

更新:使用 Spring 2.5,这应该可以帮助您入门:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:annotation-config />

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    <!-- now add some controllers -->

</beans>
于 2011-07-14T10:38:06.893 回答
2

是的,这当然是可能的。

要使用控制器注释,例如@Controller@RequestMapping确保你把

<mvc:annotation-driven/>

在你的<servletname>-servlet.xml

然后使用普通的 XML bean 表示法简单地定义您的控制器,例如:

<bean class="com.company.controllers.AController">
    <property name="propertyName" ref="beanId" />
</bean>

这些 bean refs 也可以来自applicationContext.xml您定义的任何其他web.xml

于 2011-07-14T10:36:31.743 回答