在使用mybatis 3.0的annotation之后,会产生大量mapper接口文件。
使用下面这个类可以提取这些mapper的清单
public final class MybatisMapperScanner extends
ClassPathScanningCandidateComponentProvider {
{
addIncludeFilter(new AnnotationTypeFilter(Repository.class));
// exclude package-info.java
addExcludeFilter(new TypeFilter() {
@Override
public boolean match(final MetadataReader metadataReader,
final MetadataReaderFactory metadataReaderFactory)
throws IOException {
final String className = metadataReader.getClassMetadata()
.getClassName();
return className.endsWith("package-info");
}
});
}
/** * */
public MybatisMapperScanner() {
super(false);
}
/**
* 搜索所有的mybatis mapper
*
* @param packageName
* 包名,如"com.iteye.strongzhu"
*
* @return 所有的mapper清单
*/
@SneakyThrows(ClassNotFoundException.class)
public Set<Class<Object>> scanMapper(final String packageName) {
final Set<BeanDefinition> components = findCandidateComponents(packageName);
final Set<Class<Object>> mybatisMapperList = new HashSet<Class<Object>>();
for (final BeanDefinition component : components) {
@SuppressWarnings("unchecked")
final Class<Object> cls = (Class<Object>) Class.forName(component
.getBeanClassName());
mybatisMapperList.add(cls);
}
return mybatisMapperList;
}
/*
* (non-Javadoc)
*
* @see org.springframework.context.annotation.
* ClassPathScanningCandidateComponentProvider
* #isCandidateComponent(org.springframework
* .beans.factory.annotation.AnnotatedBeanDefinition)
*/
@Override
protected boolean isCandidateComponent(
final AnnotatedBeanDefinition beanDefinition) {
return (beanDefinition.getMetadata().isInterface() && beanDefinition
.getMetadata().isIndependent());
}
}