代码

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. CSS揭秘之《多重边框》

    1.box-shadow还接受第四个参数(称作"扩张半径"), 通过指定正值或负值, 可以让投影面积加大或者减小2.如果我们想要一道实线边框其实也是可以通过box-shadow来模 ...

  2. java中什么是局部内部类Local inner class?

    5.局部内部类Local inner class 马克-to-win:什么叫局部内部类?内部类声明位置:1.它的外部类的范围之内.2.在几个程序块的范围之内.例如,由方法定义的块中或甚至在for循环体 ...

  3. Hadoop真分布式实现SSH免密登录

    首先需要两台服务器(CentOS安装Linux见:https://www.cnblogs.com/syq816/p/12355115.html) 伪分布式的搭建见:https://www.cnblog ...

  4. 一像素边框的问题(使不同dpr设备完美显示1px的border)

    问题:不同dpr的屏幕有不同的屋里像素值,而我们css像素的1px由于不同屏幕的渲染会导致宽度并不一样: 例如: dpr为2的retina屏幕是有四个物理像素点(真实屏幕上的点)组成一个逻辑(css) ...

  5. Promise原理实现(一):前置知识点

      实现promise首先需要了解如下知识点: 1: 高阶函数 (一个函数作为另外一个函数的参数,这个包含的函数就是高阶函数): outer是一个高阶函数,inner函数作为一个参数传递:此处也是闭包 ...

  6. 关于表达式&& 和 || 有多项的时候的取值

    && 表达式只有两项的时候,如果表达式为false, 返回为false 的那一个 ,为true的时候    返回最后一个值 ||  只有两项的时候,返回为true 的那一个;都为fal ...

  7. 移动端页面中点击input输入框的时候弹出的键盘将输入框挡住的问题

    使用的是vux框架, 以为是框架问题, 后来发现是把当前页面的高度写死为了height:200%: 只要把高度去掉就能让页面自动弹到输入框的上方:

  8. vue中执行npm run build报错解决方法?

    遇到了执行npm run build 后报错: [build:js ] Module not found: Error: Can't resolve 'scss-loader' in 'D:\work ...

  9. 地铁系统ajax人性化操作

    根据选择的城市不同,显示的地铁系统和线路图也不同

  10. 小程序 -- 去掉button默认样式

    button { position:relative; display:block; margin-left:auto; margin-right:auto; padding-left:14px; p ...