简体   繁体   中英

Configuring Spring 4 MVC Controller

I'm trying to learn the basics of Spring 4 MVC for Restful web services, but that's not the problem here.

In my @RestController, I'd like to use Spring's Unmarshaller Interface, and specifically use Jaxb2Marshaller. So, for now, I have....

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

which works. But how do I do the same thing either via @Autowired to set the unmarshaller, or use Spring's dependency injection via the XML configuration files?

My dispatcher-servlet.xml file is simple...

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

Many Thanks for your help & suggestions.

Chris

You can use a configuration class

@Configuration
public MyClass{

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

then in your controller

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

// rest of class
}

The bean definition you can also make it in a xml file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM