最近我们部门有个小项目,用来管理这个公司所有项目用到的代码表,例如国家代码、行政区划代码等。这个项目的功能其实很少,就是简单的修改、查询、新增和逻辑删除。但是为每张表都写一套增删改查的页面和一套service,工作量巨大,且维护很困难。我们发现各个表的业务其实都很类似,如果能写一套通用的service代码,在web层根据表名动态调用,在通用的jsp上生成想要的数据,那就只需要写一套代码就可以完成所有代码表的操作了。

  完成这个要求第一个想到的当然是用反射啊,通过表名反射生成相应的QO、DAO,通过调用相应的dao方法,来实现相关功能。但是当我通过反射实例出dao,再执行相应的方法时,方法内一直报错。通过查询资料,可以通过方法得到已经被Spring托管的bean( XX.getBean("xxx") ),于是我改成根据表名动态获取dao,通过反射找到相应方法,执行相应方法,问题就迎刃而解了。

  

  首先是获取被Spring托管类的工具类

 import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service; /**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
*/
@Service
public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); /**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
public void setApplicationContext(ApplicationContext applicationContext) {
logger.debug("注入ApplicationContext到SpringContextHolder:" + applicationContext); if (SpringContextHolder.applicationContext != null) {
logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:"
+ SpringContextHolder.applicationContext);
} SpringContextHolder.applicationContext = applicationContext; //NOSONAR
} /**
* 实现DisposableBean接口,在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
SpringContextHolder.clear();
} /**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
} /**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clear() {
logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
applicationContext = null;
} /**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
}

之后是service层代码

 public interface CommonService {

     /**
* 分页查询
* @param object 表名
* @return Page<> 列表
*/
Object findPageList(String name);
}
 /**
*
* 通用service
*/
@Service("commonService")
public class CommonServiceImpl implements CommonService {
/**
* 分页查询
* @param object 表名
* @return Page<> 列表
*/
public Object findPageList(String name) {
try {
//获取QO
Class clQO = Class.forName("org.xxx.domain.qo."+name+"QO");
Object objectQO = clQO.newInstance();
//设置未删除
Field deltIndc = clQO.getDeclaredField("deltIndc");
deltIndc.setAccessible(true);
deltIndc.set(objectQO, "0");
//首字母小写 拼成xxxxDao
String nameDao =
(new StringBuilder()).append(
Character.toLowerCase(name.charAt(0))).append(name.substring(1)).toString()
+"Dao";
//获取被Spring托管的dao层实例
Object objDao = SpringContextHolder.getBean(nameDao);
Method[] ms = objDao.getClass().getMethods();
for(Method m:ms){
//找到find方法 执行
if("find".equals(m.getName())){
return m.invoke(objDao, new Object[]{objectQO});
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

controller

 @Controller
public class CommonAction { @Autowired(required = false)
private CommonService commonService; @RequestMapping("getPage")
public @ResponseBody Object getPage(String name) {
//"PltmPubNews"
return commonService.findPageList(name);
} }

  这样就可以根据表名动态查询了。

相关链接  :   http://blog.csdn.net/gaopeng0071/article/details/50511341

反射和动态加载bean 完成 通用servie的更多相关文章

  1. Java反射、动态加载(将java类名、方法、方法参数当做参数传递,执行方法)

    需求:将java类名.方法.方法参数当做参数传递,执行方法.可以用java的动态加载实现   反射的过程如下:     第一步:通过反射找到类并创建实例(classname为要实例化的类名,由pack ...

  2. C# 反射实现动态加载程序集

    原文:https://blog.csdn.net/pengdayong77/article/details/47622235 在.Net 中,程序集(Assembly)中保存了元数据(MetaData ...

  3. C#实现反射调用动态加载的DLL文件中的方法

    反射的作用:1. 可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型 2. 应用程序需要在运行时从某个特定的程序集中载入一个特定的类型,以便实现某个任务时可以用到反射.3. ...

  4. Java动态加载类在功能模块开发中的作用

    Java中我们一般会使用new关键字实例化对象然后调用该对象所属类提供的方法来实现相应的功能,比如我们现在有个主类叫Web类这个类中能实现各种方法,比如用户注册.发送邮件等功能,代码如下: /* * ...

  5. c#实现动态加载Dll(转)

    c#实现动态加载Dll 分类: .net2009-12-28 13:54 3652人阅读 评论(1) 收藏 举报 dllc#assemblynullexceptionclass 原理如下: 1.利用反 ...

  6. c#实现动态加载Dll

    原文:c#实现动态加载Dll 原理如下: 1.利用反射进行动态加载和调用. Assembly assembly=Assembly.LoadFrom(DllPath); //利用dll的路径加载,同时将 ...

  7. C# 动态加载(转)

    原文链接地址:http://blog.csdn.net/lanruoshui/article/details/5090710 原理如下: 1.利用反射进行动态加载和调用. Assembly assem ...

  8. .Net Core利用反射动态加载类库的方法(解决类库不包含Nuget依赖包的问题)

    在.Net Framework时代,生成类库只需将类库项目编译好,然后拷贝到其他项目,即可引用或动态加载,相对来说,比较简单.但到了.Net Core时代,动态加载第三方类库,则稍微麻烦一些. 一.类 ...

  9. C# 利用反射动态加载dll

    笔者遇到的一个问题,dll文件在客户端可以加载成功,在web端引用程序报错.解决方法:利用反射动态加载dll 头部引用加: using System.Reflection; 主要代码: Assembl ...

随机推荐

  1. Tools - 浏览器Firefox

    简介 http://www.mozilla.org/ 中文官网:http://www.firefox.com.cn/ https://www.mozilla.org/zh-CN/firefox/ Mo ...

  2. Failed to start docker.service: Unit not found.

    安装教程参考: https://docs.docker.com/install/linux/docker-ce/centos/#install-docker-ce-1 https://yq.aliyu ...

  3. 传染病传播模型(SIS)Matlab代码

    function spreadingability=sir(A,beta,mu) for i=1:length(A) for N=1:50%随机次数 InitialState=zeros(length ...

  4. 课程一(Neural Networks and Deep Learning),第一周(Introduction to Deep Learning)—— 0、学习目标

    1. Understand the major trends driving the rise of deep learning.2. Be able to explain how deep lear ...

  5. Feign status 400 reading 问题分析

    背景:项目使用的是微服务架构,采用springboot来开发,所有的服务都是基于内嵌tomcat来运行 问题:项目部署到测试环境之后,偶尔在后台日志会看到这样的日志:Feign status 400 ...

  6. 微信小程序开发环境搭建

    关注,QQ群,微信应用号社区 511389428 微信小程序可谓是今天最火的一个名词了,一经出现真是轰炸了整个开发人员,当然很多App开发人员有了一个担心,微信小程序的到来会不会给移动端App带来一个 ...

  7. 测试驱动开发 - Test-Driven Development

    TDD 开发模式流程: 编写测试用例 -> 运行测试用例 –> 编写项目代码 -> 运行测试用例 -> 重构代码 优点: 1.TDD 开发中加入了回归测试,这样就确保了之前的功 ...

  8. docker 非root用户修改mount到容器的文件出现“Operation not permitted

    使用环境centos7 x86-64 内核版本4.19.9 docker使用非root用户启动,daemon.json配置文件内容如下: # cat daemon.json { "usern ...

  9. 轻量级web富文本框——wangEditor使用手册(6)——配置“上传图片”功能

    最新版wangEditor: 配置说明:http://www.wangeditor.com/doc.html demo演示:http://www.wangeditor.com/wangEditor/d ...

  10. lucene-01-简介

    1, 介绍 hadoop作者开发的 hdfs最开始作为netch的文件存储来使用的 2, 存储结构 lucene快的原因, 是因为添加数据的时候会对数据进行分词, 将分词后的词建立索引, 存储到索引库 ...