MyBatis扫描通过VFS来实现
在Spring Boot中,由于是嵌套Jar,导致Mybatis默认的VFS实现DefaultVFS无法扫描嵌套Jar中的类。
解决办法,实现自定义的VFS,参考DefaultVFS增加对Spring Boot嵌套JAR的处理。
以下为SpringBootVFS
import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.ibatis.io.VFS; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; /** * Spring Boot集成MyBatis打包成jar时,找不到类的问题 * @author yuejing */ public class SpringBootVFS extends VFS { @Override public boolean isValid() { return true; } @Override protected List<String> list(URL url, String path) throws IOException { ClassLoader cl = this.getClass().getClassLoader(); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl); Resource[] resources = resolver.getResources(path + "/**/*.class"); List<Resource> resources1 = Arrays.asList(resources); List<String> resourcePaths = new ArrayList<String>(); for (Resource resource: resources1) { resourcePaths.add(preserveSubpackageName(resource.getURI(), path)); } return resourcePaths; } private static String preserveSubpackageName(final URI uri, final String rootPath) { final String uriStr = uri.toString(); final int start = uriStr.indexOf(rootPath); return uriStr.substring(start, uriStr.length()); } }
在创建sqlSessionFactoryBean时加入VFS的使用
@Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception { //解决myBatis下 不能嵌套jar文件的问题 VFS.addImplClass(SpringBootVFS.class); SqlSessionFactoryBean fb = new SqlSessionFactoryBean(); // 指定数据源(这个必须有,否则报错) fb.setDataSource(ds); String typeAliasesPackage = "com.frame.sys.pojo;" + "com.frame.user.pojo;" + "com.frame.dep.pojo;" + "com.bps.crm.pojo"; fb.setTypeAliasesPackage(typeAliasesPackage); List<Resource> resources = new ArrayList<Resource>(); resources.addAll(Arrays.asList(new PathMatchingResourcePatternResolver() .getResources("classpath*:com/frame/sys/dao/oracle/*.xml"))); resources.addAll(Arrays.asList(new PathMatchingResourcePatternResolver() .getResources("classpath*:com/frame/user/dao/oracle/*.xml"))); Resource configLocation = new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"); fb.setConfigLocation(configLocation); return fb.getObject(); }
至此该问题已经解决,启动测试下吧。