【发布时间】:2018-05-28 13:05:57
【问题描述】:
我正在用 Spring 4 MVC 替换我的 Jersey Rest 控制器。所以我将所有控制器都转换为一个spring mvc RestController。问题是我无法让控制器工作。这是我的控制器:
@RestController
@RequestMapping("/person")
public class PersonController {
// .... //
// Spring xml injections
private PersonService personService;
public void setPersonService(PersonService personService) {
this.personService = personService;
}
}
bean 使用 xml 配置进行配置 -> 人豆.xml:
<bean id="personController" class="de.some.package.PersonController">
<property name="personService" ref="personService"/>
</bean>
整个应用程序一起构建在一个名为 beans.xml 的文件中 -> bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<import resource="classpath:spring/person-beans.xml"/>
<!-- and some more.. -->
</beans>
这是我的 web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>RESTServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>RESTServlet</servlet-name>
<url-pattern>/ws/*</url-pattern>
</servlet-mapping>
我想我需要补充一下:
<context:component-scan base-package="de.some.package" />
<mvc:annotation-driven />
为了使 @RestController 注释正常工作,但随后注入到我的 PersonController 类为空(所以这里是 personService)。
有没有办法将 beans.xml 中的 spring 配置与 @RestController 注释一起使用?
【问题讨论】:
-
如您所说,如果您添加
<mvc:annotation-driven />,您将能够同时拥有注解和Spring xml配置文件。 -
这个
应该放在哪里? -
根据您向我们展示的内容,在您的
beans.xml文件中,这似乎是您 Spring 配置的开始。 -
好吧,这似乎有点用。我想我的问题是我之前一起使用了组件扫描和注释驱动。如果您愿意,可以回答问题,我会将其标记为解决方案
标签: java spring spring-mvc