Mybatis3.2不支持Ant通配符TypeAliasesPackage扫描的解决方案 (3)

从这个源码比较简单的分析过程,我们并没有找到支持所谓通配符的方法,通过类加载的话也是要传个相对路径去遍历,不过我上面描述的业务场景是要兼容通配符的情况的,一般不会去改包名,假如这个项目有一定规模的话。

下面给出我的解决方案:

package com.muses.taoshop.common.core.database.annotation; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.util.ClassUtils; import static com.muses.taoshop.common.core.database.config.BaseConfig.ENTITY_PACKAGES; public class AnnotationConstants { public static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; public final static String PACKAGE_PATTERN = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(ENTITY_PACKAGES) + DEFAULT_RESOURCE_PATTERN; }

写一个扫描类,代码参考Hibernate的AnnotationSessionFactoryBean源码

package com.muses.taoshop.common.core.database.annotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import java.io.IOException; import java.util.*; import org.springframework.core.io.Resource; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.thymeleaf.util.StringUtils; import static com.muses.taoshop.common.core.database.annotation.AnnotationConstants.PACKAGE_PATTERN; /** * <pre> * TypeAlicsesPackage的扫描类 * </pre> * * @author nicky * @version 1.00.00 * <pre> * 修改记录 * 修改后版本: 修改人: 修改日期: 2018.12.01 18:23 修改内容: * </pre> */ @Component public class TypeAliasesPackageScanner { protected final static Logger LOGGER = LoggerFactory.getLogger(TypeAliasesPackageScanner.class); private static ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); /* private TypeFilter[] entityTypeFilters = new TypeFilter[]{new AnnotationTypeFilter(Entity.class, false), new AnnotationTypeFilter(Embeddable.class, false), new AnnotationTypeFilter(MappedSuperclass.class, false), new AnnotationTypeFilter(org.hibernate.annotations.Entity.class, false)};*/ public static String getTypeAliasesPackages() { Set<String> packageNames = new TreeSet<String>(); //TreeSet packageNames = new TreeSet(); String typeAliasesPackage =""; try { //加载所有的资源 Resource[] resources = resourcePatternResolver.getResources(PACKAGE_PATTERN); MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver); //遍历资源 for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader reader = readerFactory.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); //eg:com.muses.taoshop.item.entity.ItemBrand LOGGER.info("className : {} "+className); try{ //eg:com.muses.taoshop.item.entity LOGGER.info("packageName : {} "+Class.forName(className).getPackage().getName()); packageNames.add(Class.forName(className).getPackage().getName()); }catch (ClassNotFoundException e){ LOGGER.error("classNotFoundException : {} "+e); } } } } catch (IOException e) { LOGGER.error("ioException =>: {} " + e); } //集合不为空的情况,拼装一下数据 if (!CollectionUtils.isEmpty(packageNames)) { typeAliasesPackage = StringUtils.join(packageNames.toArray() , ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); }else{ LOGGER.info("set empty,size:{} "+packageNames.size()); } return typeAliasesPackage; } }

然后刚才的Mybatis配置类改一下,主要改 String typeAliasesPackage = packageScanner.getTypeAliasesPackages();通过扫描类去获取一下,重点代码在TypeAliasesPackageScanner 扫描类

package com.muses.taoshop.common.core.database.config; //省略jar进入代码 @MapperScan( basePackages = MAPPER_PACKAGES, annotationClass = MybatisRepository.class, sqlSessionFactoryRef = SQL_SESSION_FACTORY ) @EnableTransactionManagement @Configuration public class MybatisConfig { //省略其它代码,主要看sqlSessionFactory配置 @Primary @Bean(name = SQL_SESSION_FACTORY) public SqlSessionFactory sqlSessionFactory(@Qualifier(DATA_SOURCE_NAME)DataSource dataSource)throws Exception{ //SpringBoot默认使用DefaultVFS进行扫描,但是没有扫描到jar里的实体类 VFS.addImplClass(SpringBootVFS.class); SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); //factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml")); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try{ factoryBean.setMapperLocations(resolver.getResources("classpath*:/mybatis/*Mapper.xml")); String typeAliasesPackage = packageScanner.getTypeAliasesPackages(); //设置一下TypeAliasesPackage factoryBean.setTypeAliasesPackage(typeAliasesPackage); SqlSessionFactory sqlSessionFactory = factoryBean.getObject(); return sqlSessionFactory; }catch (Exception e){ e.printStackTrace(); throw new RuntimeException(); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpjpfx.html