开发者

Spring MVC 3.0 - Service layer using annonations

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?


  1. Create a FactoryBean that creates one of all possible instances
  2. Use the thread local holder RequestAttributes to obtain the request
  3. Make the controller of @Scope("request")
  4. Inject the service by interface

That should make it easy for the controller. But it is an ugly approach. Here is another one:

  1. Inject a List<YourInterface>
  2. Define a method in the interface getImplementationId()
  3. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜