Spring MVC 3.0 - 使用注解的服务层 [英] Spring MVC 3.0 - Service layer using annonations

查看:28
本文介绍了Spring MVC 3.0 - 使用注解的服务层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Spring MVC 应用程序中,只有一个 Controller 类,

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}

}

我的输入是 JSON 格式,我使用 Jackson 将其转换为 Java 对象.现在,基于 Java 对象中的属性,我想发送到适当的服务类.如果是,

My input is in the form of JSON and I use Jackson for converting it 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

所有这些服务类都将实现一个基本接口.我不想在我的 Java 代码中进行这个实例化.如何将其移动到配置文件.如何根据请求值动态注入这些对象.请注意,我正在使用注释.我是 Spring 新手.请指教

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

包括我的解决方案
在我的 dispatcher.xml 中,

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

在我的控制器中,

@Resource 私有映射 myMap;

在控制器内部的方法中,
MyService myService = (MyService) Class.forName((String)myMap.get(myRequest.getValue())).newInstance();System.out.println("我的价值" + myService.doService());

and in the method inside controller,
MyService myService = (MyService) Class.forName((String)myMap.get(myRequest.getValue())).newInstance(); System.out.println("My value" + myService.doService());

可以看出,已经使用 Java 反射从我的 XML 返回的字符串中获取实例.这是正确的方法吗?

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. 创建一个 FactoryBean 来创建所有可能的实例之一
  2. 使用线程本地持有者RequestAttributes获取请求
  3. 制作@Scope("request")
  4. 的控制器
  5. 通过接口注入服务

这对控制器来说应该很容易.但这是一种丑陋的方法.这是另一个:

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

  1. 注入一个List
  2. 在接口中定义一个方法getImplementationId()
  3. 在每个请求上迭代列表并选择返回正确 id 的实现

这种情况的一种变体是:

A variation of this would be to either:

  • 使用键预填充 Map - 来自 json 的键和值 - 特定的实现
  • 在实现 bean 名称中包含 jsod 键并注入一个 Map

然后按键查找

这篇关于Spring MVC 3.0 - 使用注解的服务层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆