我正在用 Spring 4 MVC 替换我的 Jersey Rest Controller 。所以我将所有 Controller 转换为 spring mvc RestController。问题是我无法让 Controller 工作。这是我的 Controller :
@RestController
@RequestMapping("/person")
public class PersonController {
// .... //
// Spring xml injections
private PersonService personService;
public void setPersonService(PersonService personService) {
this.personService = personService;
}
}
bean 使用 xml 配置进行配置 -> person-beans.xml:
<bean id="personController" class="de.some.package.PersonController">
<property name="personService" ref="personService"/>
</bean>
完整的应用程序一起构建在一个名为 beans.xml 的文件中 -> beans.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 注释正常工作,但注入(inject)到我的 PersonController 类中的是 null(所以这里是 personService)。
有没有办法将beans.xml中的spring配置与@RestController注释一起使用?
最佳答案
正如你所说,如果你添加 <mvc:annotation-driven />
在你的beans.xml
文件,您将能够同时拥有注释和 Spring xml 配置文件
关于java - Spring @RestController 注释,带有来自 beans.xml 的根上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50567202/