Injecting properties into Spring Rest Controller via XML



Right now I have a Spring based RESTful web-app. I'm very new to REST and so I followed some tutorials online. I built my web.xml, my rest-servlet.xml that uses the component-scan tag and loads up my RestController class which uses the @RestController annotation. (All of the code is posted below)


My issue is that none of these tutorials show me how to inject beans into my controller via an ApplicationContext.xml. I've found ways to inject using annotations, but I really want to use xml configuration. In my example below I have three database clients that I want to be wired in with the RestController when it starts up.


Any suggestions on how to load the ApplicationContext.xml on startup so that my RestController servlet receives the correct instances of the database clients?


web.xml



<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>


rest-servlet.xml



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:context="http://ift.tt/GArMu7"
xmlns:mvc="http://ift.tt/1bHqwjR" xmlns:xsi="http://ift.tt/ra1lAU"
xmlns:p="http://ift.tt/1jdM0fE"
xsi:schemaLocation="
http://ift.tt/GArMu6
http://ift.tt/1cnl1uo
http://ift.tt/GArMu7
http://ift.tt/1ldEMZY
http://ift.tt/1bHqwjR
http://ift.tt/1kF4x7W">
<context:component-scan base-package="com.helloworld.example" />
<mvc:annotation-driven />
</beans>


RestController.java



package com.helloworld.example;


import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/service/greeting")
public class SpringServiceController {

@Autowired
DBClient1 dbClient1;

@Autowired
DBClient2 dbClient2;

@Autowired
DBClient3 dbClient3;


@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String getGreeting(@PathVariable String name) {
String result="Hello "+name + " " dbClient1.toString(); // this is a test to see if the wiring worked
return result;
}
}


applicationContext.xml



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/1jdM0fG">

<bean id="dbClient1" class="com.helloworld.example.DBClient1"/>

<bean id="dbClient2" class="com.helloworld.example.DBClient2"/>

<bean id="dbClient3" class="com.helloworld.example.DBClient3"/>

</beans>

No comments:

Post a Comment