1. 程式人生 > >Spring Boot整合MyBatis打包成jar時,setTypeAliasesPackage("xxx")找不到類的問題

Spring Boot整合MyBatis打包成jar時,setTypeAliasesPackage("xxx")找不到類的問題

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();
	}

 

至此該問題已經解決,啟動測試下吧。