代码

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask; import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Repository; /**
* 定时扫描并动态加载mybatis的SQL配置文件,刷新sql mapper cache,可以在修改xml后不用重启tomcat也能生效
*
* 扫描参数:<br/>
* 1.RELOAD_INTERVAL:扫描时间间隔=3s<br/>
* 2.XML_RESOURCE_PATTERN:当前CLASSPATH下xml通配符<br/>
* 3.SESSION_FACTORY_BEAN_NAME:数据源session factory名称<br/>
* 备注:本类在开发环境下使用,正式发布后注释掉applicationContext.xml中id=MyBatisDynamicLoader的bean
*
* @author MF
* @version 1.0
*/
@Repository("XMLMapperLoader")
public class XMLMapperLoader implements InitializingBean, ApplicationContextAware {
// 扫描时间间隔
private static final long RELOAD_INTERVAL = 3000; private final HashMap<String, String> mappers = new HashMap<String, String>();
private volatile ConfigurableApplicationContext context = null;
private volatile Scanner scanner = null; @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = (ConfigurableApplicationContext) applicationContext;
} @Override
public void afterPropertiesSet() throws Exception {
try {
scanner = new Scanner();
new Timer(true).schedule(new TimerTask() {
public void run() {
try {
if (scanner.isChanged()) {
scanner.reloadXML();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 5 * 1000, RELOAD_INTERVAL);
} catch (Exception e1) {
e1.printStackTrace();
}
} class Scanner {
private static final String XML_RESOURCE_PATTERN =
ResourcePatternResolver.CLASSPATH_URL_PREFIX + "mapper/*/*.xml";
private static final String SESSION_FACTORY_BEAN_NAME = "sqlSessionFactory"; private final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public Scanner() throws IOException {
Resource[] resources = findResource();
if (resources != null) {
for (Resource resource : resources) {
String key = resource.getURI().toString();
String value = getMd(resource);
mappers.put(key, value);
}
}
} public void reloadXML() throws Exception {
// 如果是单数据源用这个
// SqlSessionFactory factory = context.getBean(SqlSessionFactory.class);
/* 这里指定数据源,多数据源环境使用 */
System.out.println("========== Reload SQL Cache on [" + SESSION_FACTORY_BEAN_NAME + "] ==========");
SqlSessionFactory factory = (SqlSessionFactory) context.getBean(SESSION_FACTORY_BEAN_NAME);
Configuration configuration = factory.getConfiguration();
removeConfig(configuration);
for (Resource resource : findResource()) {
System.out.println(resource.getFilename());
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(), configuration,
resource.toString(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
} finally {
ErrorContext.instance().reset();
}
}
System.out.println("========== Reload end ==========");
} private void removeConfig(Configuration configuration) throws Exception {
Class<?> classConfig = configuration.getClass();
clearMap(classConfig, configuration, "mappedStatements");
clearMap(classConfig, configuration, "caches");
clearMap(classConfig, configuration, "resultMaps");
clearMap(classConfig, configuration, "parameterMaps");
clearMap(classConfig, configuration, "keyGenerators");
clearMap(classConfig, configuration, "sqlFragments");
clearSet(classConfig, configuration, "loadedResources");
} @SuppressWarnings("rawtypes")
private void clearMap(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
Field field = classConfig.getDeclaredField(fieldName);
field.setAccessible(true);
((Map) field.get(configuration)).clear();
} @SuppressWarnings("rawtypes")
private void clearSet(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
Field field = classConfig.getDeclaredField(fieldName);
field.setAccessible(true);
((Set) field.get(configuration)).clear();
} public boolean isChanged() throws IOException {
boolean isChanged = false;
for (Resource resource : findResource()) {
String key = resource.getURI().toString();
String value = getMd(resource);
if (!value.equals(mappers.get(key))) {
isChanged = true;
mappers.put(key, value);
}
}
return isChanged;
} private Resource[] findResource() throws IOException {
return resourcePatternResolver.getResources(XML_RESOURCE_PATTERN);
} private String getMd(Resource resource) throws IOException {
return new StringBuilder()
.append(resource.contentLength())
.append("-")
.append(resource.lastModified())
.toString();
}
}
}

Spring加载方式

加载方式:在Spring XML文件中加入:(发布生产时要注释掉,不启动)
<!-- MyBatis 热加载,修改无需重新部署web容器的bean -->
<bean id ="MyBatisDynamicLoader" class= "com.xxx.XMLMapperLoader"/>

MyBatis热部署的更多相关文章

  1. MyBatis-HotSwap, MyBatis热部署

    https://github.com/xiaochenxinqing/MyBatis-HotSwap   1 https://github.com/xiaochenxinqing/MyBatis-Ho ...

  2. mybatis 热部署xml文件(spring boot和springmvc两种方式)

    参考:http://thinkgem.iteye.com/blog/2304557 步骤:1.创建两个java类 (1)MapperRefresh.java   :用于刷新mapper (2)SqlS ...

  3. springboot集成mybatis(逆向工程),热部署以及整合Swagger2

    本文是作者原创,版权归作者所有.若要转载,请注明出处. springboot集成mybatis和mybatis-generator插件 1.新建Springboot项目(略) 2.导入相关依赖 < ...

  4. springboot整合mybatis增删改查(二):springboot热部署

    SpringBoot整合热部署 传统情况下, 我们用idea运行springboot程序时, 如果我们需要修改类里的方法,或者其他信息 我们需要修改完保存,并且重启springboot,有时候会很浪费 ...

  5. SpringBoot+gradle+idea实现热部署和热加载

    前言 因为之前使用myeclipes的同学就知道,在使用myeclipes的时候,java文件或者jsp文件写完之后会被直接热加载到部署的容器中,从而在开发的时候,不同经常去重启项目,从而达到了增加开 ...

  6. SpringBoot03 项目热部署

    1 问题 在编写springBoot项目时,经常需要修改代码:但是每次修改代码后都需重新启动,修改的代码才会生效 2 这么实现IDEA能够像Eclipse那样保存过后就可以自动进行刷新呢 将sprin ...

  7. SpringBoot实现热部署(修改class不需要重启)

    热部署: devtools可以实现页面热部署(即页面修改后会立即生效, 这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false来实 ...

  8. SpringBoot热部署的实现方式

    一:热部署的实现 1.使用Spring-boot-devtools 2.使用Spring Loaded 二:devtools(推荐) 一般情况下直接在pom.xml文件添加下面的依赖即可,但eclip ...

  9. IDEA 热部署- 自动编译设置

    原文:https://www.cnblogs.com/TechSnail/p/7690829.html    &&   https://blog.csdn.net/qq_3129357 ...

随机推荐

  1. catkin编译系统

    引言 最近项目中遇到一个需求:将 C++ 程序 (不是 ROS node,只是普通的 C++ 程序)中的变量发布到 ROS topic 上,以便 ROS 中的其他 node 进行后续处理. 原 C++ ...

  2. 基于Node的React图片上传组件实现

    写在前面 红旗不倒,誓把JavaScript进行到底!今天介绍我的开源项目 Royal 里的图片上传组件的前后端实现原理(React + Node),花了一些时间,希望对你有所帮助. 前端实现 遵循R ...

  3. python-输入输出-计算字符串中的数

    将字符串中的每个数都抽取出来,然后统计所有数的个数并求和. 输入格式: 一行字符串,字符串中的数之间用1个空格或者多个空格分隔. 输出格式: 第1行:输出数的个数.第2行:求和的结果,保留3位小数. ...

  4. .NET程序设计实验二

    实验二  面向对象程序设计 一.实验目的 1. 理解类的定义.继承等面向对象的的基本概念: 2. 掌握C#语言定义类及其各种成员(字段,属性,方法)的方法: 3. 掌握方法覆盖的应用: 4. 掌握接口 ...

  5. 获取iframe引入页面内的元素

    在web开发中,经常会用到iframe,难免会碰到需要在父窗口中使用iframe中的元素.或者在iframe框架中使用父窗口的元素.js在父窗口中获取iframe中的元素1.    格式:window ...

  6. 解决IDEA中控制台输出乱码

    1. 修改VM Options(2种方法) 第一种,直接修改Tomcat中的 VM Options,这种只对当前项目有效 (1)先点击 Run -> Edit Configurations- 2 ...

  7. 搭建 LNMP 环境

    搭建 LNMP 环境 搭建 Nginx 静态服务器 安装 Nginx 使用 yum 安装 Nginx: yum install nginx -y 修改 /etc/nginx/conf.d/defaul ...

  8. 手把手带你撸一把springsecurity框架源码中的认证流程

    提springsecurity之前,不得不说一下另外一个轻量级的安全框架Shiro,在springboot未出世之前,Shiro可谓是颇有统一J2EE的安全领域的趋势. 有关shiro的技术点 1.s ...

  9. 01 | 堆、栈、RAII:C++里该如何管理资源?(极客时间笔记)

    基本概念 堆,英文是 heap,在内存管理的语境下,指的是动态分配内存的区域.这个堆跟数据结构里的堆不是一回事.这里的内存,被分配之后需要手工释放,否则,就会造成内存泄漏. C++ 标准里一个相关概念 ...

  10. Azure Virtual Desktop(一)创建配置管理

    一,引言 Azure 虚拟创面是一项 Azure 服务,可以让我们管理: 1)VDI(虚拟桌面基础架构) 2)云端的 RDSH:RDSH 是 RDS(远程桌面服务)中的一个角色.这些类型的服务器用于托 ...