使用beans.xml中的根上下文的Spring @RestController注释

时间:2018-05-28 13:05:58

标签: java spring spring-mvc

我用Spring 4 MVC替换了我的Jersey Rest控制器。所以我将所有控制器转换为spring mvc RestController。问题是我无法让控制器工作。这是我的控制器:

java.lang.ClassNotFoundException: test.SimpleApp

bean配置了xml配置 - > 人-beans.xml文件:

@RestController
@RequestMapping("/person")
public class PersonController { 

    // .... //

    // Spring xml injections
    private PersonService personService;
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }
}

完整的应用程序一起构建在一个名为beans.xml的文件中 - > beans.xml中:

<bean id="personController" class="de.some.package.PersonController">
    <property name="personService" ref="personService"/>
</bean>

这是我的web.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>

我想我需要补充一下:

<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>

为了让@RestController注释工作,但是我的PersonController类的注入是null(所以这里是personService)。

有没有办法使用beans.xml中的spring配置和@RestController注释?

1 个答案:

答案 0 :(得分:1)

正如您所说,如果您在<mvc:annotation-driven />文件中添加beans.xml,您将能够同时拥有注释和Spring xml配置文件