解决myBatis下不能嵌套jar文件的问题

MyBatis扫描通过VFS来实现

Spring Boot中,由于是嵌套Jar,导致Mybatis默认的VFS实现DefaultVFS无法扫描嵌套Jar中的类。

说俗一点就是:你的项目要引入别人的jar包,别人的jar包也是有集成mybatis相关的xml文件内容的

解决办法,实现自定义的VFS,参考DefaultVFS增加对Spring Boot嵌套JAR的处理。

1:新建一个类SpringBootVfs

package com.tortoise.workflow.config;

import
lombok.extern.slf4j.Slf4j;
import
org.apache.ibatis.io.DefaultVFS;
import
org.springframework.util.ResourceUtils;

import
java.io.IOException;
import
java.net.MalformedURLException;
import
java.net.URL;
import
java.util.ArrayList;
import
java.util.List;
import
java.util.jar.JarEntry;
import
java.util.jar.JarInputStream;

@Slf4j
public class SpringBootVfs  extends DefaultVFS {

   
@Override
   
protected URL findJarForResource(URL url) throws MalformedURLException {
        url = ResourceUtils.extractJarFileURL(url)
;
        return
(isJar(url)) ? url : null;
   
}

   
@Override
   
protected boolean isJar(URL url) {
       
return url.getPath().toLowerCase().endsWith(ResourceUtils.JAR_FILE_EXTENSION)
                || url.getPath().toLowerCase().endsWith(
".war");
   
}

   
/**
     * List the names of the entries in the given {@link JarInputStream} that
     * begin with the specified {@code path}. Entries will match with or without
     * a leading slash.
     *
     * @param
jar The JAR input stream
     * @param
path The leading path to match
     * @return The names of all the matching entries
     * @throws IOException If I/O errors occur
     */
   
@Override
   
protected List<String> listResources(JarInputStream jar, String path) throws IOException {
       
// Include the leading and trailing slash when matching names
       
if (!path.startsWith("/"))
            path =
"/" + path;
        if
(!path.endsWith("/"))
            path = path +
"/";

       
// Iterate over the entries and collect those that begin with the
        // requested path
       
List<String> resources = new ArrayList<String>();
        for
(JarEntry entry; (entry = jar.getNextJarEntry()) != null;) {
           
if (!entry.isDirectory()) {
               
// Add leading slash if it's missing
               
String name = entry.getName();
                if
(!name.startsWith("/"))
                    name =
"/" + name;

               
// Check file name
               
if (name.startsWith(path) || name.startsWith("/WEB-INF/classes" + path)) {
                    resources.add(name.substring(
1)); // Trim leading slash
               
}
            }
        }
       
return resources;
   
}
}

 

2:自定义Mybatis的配置信息类MybatisConfig

配置信息:

#数据库连接驱动类名

spring.datasource.driver-class-name = com.mysql.jdbc.Driver

spring.datasource.url = jdbc:mysql://172.16.0.1:3306/portal?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false

spring.datasource.username = root

spring.datasource.password = 1234

 

 

package com.tortoise.workflow.config;

import com.alibaba.druid.proxy.jdbc.DataSourceProxy;

import com.zaxxer.hikari.HikariDataSource;

import lombok.extern.slf4j.Slf4j;

import org.apache.ibatis.io.VFS;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

  @Configuration

@Slf4j

  public class MybatisConfig {

  

  

    @Value("${spring.datasource.url}")

    private String jdbcUrl;

    @Value("${spring.datasource.username}")

    private String username;

    @Value("${spring.datasource.password}")

    private String password;
@Value("${spring.datasource.driver_class_name}")

    private String driverClassName;

  

  

  

    /**

     * 配置数据源代理,用于事务回滚

     *

     * @return The default datasource

     * @see DataSourceProxy

     */

    @Primary

    @Bean("dataSource")

    @ConfigurationProperties("spring.datasource")

    public DataSource dataSource() {

        HikariDataSource dataSource = new HikariDataSource();

        dataSource.setJdbcUrl(jdbcUrl);

        dataSource.setUsername(username);

        dataSource.setPassword(password);

        dataSource.setDriverClassName(driverClassName);

        return dataSource;

    }

  

    @Bean(name = "sqlSessionFactory")

    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) {

        //解决myBatis下 不能嵌套jar文件的问题

        VFS.addImplClass(SpringBootVfs.class);

        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

        bean.setDataSource(dataSource);

        bean.setTypeAliasesPackage("com.tortoise");

        // 分页插件

  

        //添加XML目录

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        try {

            // 添加插件

            bean.setMapperLocations(resolver.getResources("classpath*:mapping/**/*.xml"));

            return bean.getObject();

        } catch (Exception e) {

            e.printStackTrace();

            throw new RuntimeException(e);

        }

    } 

}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值