In my Spring MVC application with a single Controller class,
@Controller
public class MyController {
@RequestMapping(method = RequestMethod.POST, value = "/*.htm")
public myMethod{@RequestBody final MyRequestBean myRequest}
}
My input is in the form of JSON and I use Jackson for converting it 开发者_Go百科to Java object. Now, based on the property in the Java object, I want to send to appropriate service class. If it is,
myRequest.value == "1" -> FirstService
myRequest.value == "2" -> SecondService
All these Service classes will be implementing a basic interface. I dont want to do this instantiation in my Java code. How can I move this to a configuration file. How can I inject these objects dynamically based on the request values. Please note that am using annotations. Am new to Spring.Please advise
EDIT: To include my solution
In my dispatcher.xml,`<util:map id="myMap">
<entry key="service1" value="com.service.MyService1" />
<entry key="service2" value="com.service.MyService1" />
</util:map>`
In my controller,
@Resource private Map myMap;
and in the method inside controller,
MyService myService = (MyService) Class.forName((String)myMap.get(myRequest.getValue())).newInstance(); System.out.println("My value" + myService.doService());
As can be seen, have used Java reflection for getting the instance from the string returned from my XML. Is this the correct way?
- Create a FactoryBean that creates one of all possible instances
- Use the thread local holder
RequestAttributes
to obtain the request - Make the controller of
@Scope("request")
- Inject the service by interface
That should make it easy for the controller. But it is an ugly approach. Here is another one:
- Inject a
List<YourInterface>
- Define a method in the interface
getImplementationId()
- On each request iterate the list and pick the implwmentation that returns the proper id
A variation of this would be to either:
- prepopulate a Map with key - the key coming from json, and value - a specific impl
- Include the jsod key in the implementation bean name and inject a
Map<String, YourInterface>
Then lookup by key
精彩评论