配置Spring 4 MVC控制器

时间:2015-11-17 21:00:09

标签: java spring spring-mvc

我正在尝试学习Spring 4 MVC for Restful Web服务的基础知识,但这不是问题所在。

在我的@RestController中,我想使用Spring的Unmarshaller接口,并且特别使用Jaxb2Marshaller。所以,现在,我有......

@RestController
@RequestMapping("/postuser")
public class MyController {
    private String xsdFileName = "User.xsd";
    private Jaxb2Marshaller unmarshaller;

    public MyController() {
        unmarshaller = new Jaxb2Marshaller();
        unmarshaller.setPackagesToScan("com.mypackage");
    }
// rest of class
}

哪个有效。但是我如何通过@Autowired来设置unmarshaller,或者通过XML配置文件使用Spring的依赖注入呢?

我的dispatcher-servlet.xml文件很简单......

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:p="http://www.springframework.org/schema/p"
      xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

   <context:component-scan base-package="com.mypackage" />

   <mvc:annotation-driven />

 </beans>

非常感谢您的帮助和帮助建议。

克里斯

1 个答案:

答案 0 :(得分:1)

您可以使用配置类

@Configuration
public MyClass{

    @Bean
    public Jaxb2Marshaller unmarshaller() {
        Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
        unmarshaller.setPackagesToScan("com.mypackage");
        return unmarshaller;
    }
}

然后在您的控制器中

@RestController
@RequestMapping("/postuser")
public class MyController {
    private String xsdFileName = "User.xsd";
    @Autowired
    private Jaxb2Marshaller unmarshaller;

// rest of class
}

bean定义你也可以在xml文件中使用

<bean id="unmarshaller" class="package.Jaxb2Marshaller">
    <property name="packagesToScan">
        <value>com.mypackage</value>
    </property>
</bean>
相关问题