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

在我的@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设置反编组器,或者通过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>


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

克里斯

最佳答案

您可以使用配置类

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


您还可以在xml文件中创建bean定义

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

10-06 09:11
查看更多