美文网首页
Springboot 配置多数据源时加载不到 mapper/*.

Springboot 配置多数据源时加载不到 mapper/*.

作者: 利威尔的小陀螺 | 来源:发表于2023-04-17 02:32 被阅读0次

正确姿势👇

@Bean
    public SqlSessionFactory sqlSessionFactory(DataSource idleDataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(idleDataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml"));

        return factoryBean.getObject();
    }

一定要用 new PathMatchingResourcePatternResolver().getResources("classpath:mapper//.xml");!
getResources(),有个 s !

区别在于

  1. PathMatchingResourcePatternResolver#getResource(String location)
    直接把传入的字符串当作资源地址来加载,只会加载一个资源。
@Override
    public Resource getResource(String location) {
        return getResourceLoader().getResource(location);
    }
  1. PathMatchingResourcePatternResolver#getResources(String locationPattern)
    任务传入的是一个资源地址表达式,可能会解析出多个资源并返回资源数组。
@Override
    public Resource[] getResources(String locationPattern) throws IOException {
        Assert.notNull(locationPattern, "Location pattern must not be null");
        if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
            // a class path resource (multiple resources for same name possible)
            if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
                // a class path resource pattern
                return findPathMatchingResources(locationPattern);
            }
            else {
                // all class path resources with the given name
                return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
            }
        }
        else {
            // Generally only look for a pattern after a prefix here,
            // and on Tomcat only after the "*/" separator for its "war:" protocol.
            int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
                    locationPattern.indexOf(':') + 1);
            if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
                // a file pattern
                return findPathMatchingResources(locationPattern);
            }
            else {
                // a single resource with the given name
                return new Resource[] {getResourceLoader().getResource(locationPattern)};
            }
        }
    }

相关文章

网友评论

      本文标题:Springboot 配置多数据源时加载不到 mapper/*.

      本文链接:https://www.haomeiwen.com/subject/wqwqjdtx.html