Reputation: 401
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
Upvotes: 1
Views: 340
Reputation: 8334
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>
Upvotes: 1