Skip to content

Support excluding filter on mapper scan feature #836

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,12 @@
<version>6.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.19</version>
<optional>true</optional>
</dependency>

<dependency>
<groupId>net.bytebuddy</groupId>
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/org/mybatis/spring/annotation/MapperScan.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AliasFor;

Expand Down Expand Up @@ -195,5 +196,10 @@
* @return a flag that whether execute a property placeholder processing or not
*/
boolean processPropertyPlaceHolders() default true;

/**
* Specifies which types are not eligible for mapper scanning.
*/
ComponentScan.Filter[] excludeFilters() default {};

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.mybatis.spring.mapper.ClassPathMapperScanner;
Expand All @@ -31,10 +32,13 @@
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.*;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

Expand All @@ -54,15 +58,13 @@
*/
public class MapperScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

private ResourceLoader resourceLoader;
/**
* {@inheritDoc}
*
* @deprecated Since 2.0.2, this method not used never.
*/
@Override
@Deprecated
public void setResourceLoader(ResourceLoader resourceLoader) {
// NOP
this.resourceLoader = resourceLoader;
}

/**
Expand Down Expand Up @@ -126,6 +128,11 @@ void registerBeanDefinitions(AnnotationMetadata annoMeta, AnnotationAttributes a
basePackages.add(getDefaultBasePackage(annoMeta));
}

AnnotationAttributes[] excludeFilterArray = annoAttrs.getAnnotationArray("excludeFilters");
for (AnnotationAttributes excludeFilters : excludeFilterArray) {
builder.addPropertyValue("excludeFilters", typeFiltersFor(excludeFilters));
}

String lazyInitialization = annoAttrs.getString("lazyInitialization");
if (StringUtils.hasText(lazyInitialization)) {
builder.addPropertyValue("lazyInitialization", lazyInitialization);
Expand All @@ -145,6 +152,48 @@ void registerBeanDefinitions(AnnotationMetadata annoMeta, AnnotationAttributes a

}

private List<TypeFilter> typeFiltersFor(AnnotationAttributes filterAttributes) {

List<TypeFilter> typeFilters = new ArrayList<>();
FilterType filterType = filterAttributes.getEnum("type");

for (Class<?> filterClass : filterAttributes.getClassArray("value")) {
switch (filterType) {
case ANNOTATION:
Assert.isAssignable(Annotation.class, filterClass,
"An error occured when processing a @ComponentScan " + "ANNOTATION type filter: ");
@SuppressWarnings("unchecked")
Class<Annotation> annoClass = (Class<Annotation>) filterClass;
typeFilters.add(new AnnotationTypeFilter(annoClass));
break;
case ASSIGNABLE_TYPE:
typeFilters.add(new AssignableTypeFilter(filterClass));
break;
case CUSTOM:
Assert.isAssignable(TypeFilter.class, filterClass,
"An error occured when processing a @ComponentScan " + "CUSTOM type filter: ");
typeFilters.add(BeanUtils.instantiateClass(filterClass, TypeFilter.class));
break;
default:
throw new IllegalArgumentException("Unknown filter type " + filterType);
}
}

String[] expressionArray = filterAttributes.getStringArray("pattern");
for (String expression : expressionArray) {
String rawName = filterType.toString();
if ("REGEX".equals(rawName)) {
typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
} else if ("ASPECTJ".equals(rawName)) {
typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader()));
} else {
throw new IllegalArgumentException("Unknown filter type " + filterType);
}
}
return typeFilters;
}


private static String generateBaseBeanName(AnnotationMetadata importingClassMetadata, int index) {
return importingClassMetadata.getClassName() + "#" + MapperScannerRegistrar.class.getSimpleName() + "#" + index;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;

Expand All @@ -40,6 +41,7 @@
import org.springframework.core.NativeDetector;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;

/**
Expand Down Expand Up @@ -85,6 +87,7 @@ public class ClassPathMapperScanner extends ClassPathBeanDefinitionScanner {
private Class<? extends MapperFactoryBean> mapperFactoryBeanClass = MapperFactoryBean.class;

private String defaultScope;
private List<TypeFilter> excludeFilters;

public ClassPathMapperScanner(BeanDefinitionRegistry registry) {
super(registry, false);
Expand Down Expand Up @@ -134,6 +137,10 @@ public void setMarkerInterface(Class<?> markerInterface) {
this.markerInterface = markerInterface;
}

public void setExcludeFilters(List<TypeFilter> excludeFilters) {
this.excludeFilters = excludeFilters;
}

public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
Expand Down Expand Up @@ -219,6 +226,13 @@ protected boolean matchClassName(String className) {
String className = metadataReader.getClassMetadata().getClassName();
return className.endsWith("package-info");
});

// exclude types declared by MapperScan.excludeFilters
if (excludeFilters != null && excludeFilters.size() > 0) {
for (TypeFilter excludeFilter : excludeFilters) {
addExcludeFilter(excludeFilter);
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import static org.springframework.util.Assert.notNull;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.Optional;

Expand All @@ -39,6 +40,7 @@
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;

/**
Expand Down Expand Up @@ -109,6 +111,8 @@ public class MapperScannerConfigurer

private Class<?> markerInterface;

private List<TypeFilter> excludeFilters;

private Class<? extends MapperFactoryBean> mapperFactoryBeanClass;

private ApplicationContext applicationContext;
Expand Down Expand Up @@ -191,6 +195,18 @@ public void setMarkerInterface(Class<?> superClass) {
this.markerInterface = superClass;
}

/**
* Specifies which types are not eligible for the mapper scanner.
* <p>
* The scanner will exclude types that define with excludeFilters.
*
* @param excludeFilters
* list of TypeFilter
*/
public void setExcludeFilters(List<TypeFilter> excludeFilters) {
this.excludeFilters = excludeFilters;
}

/**
* Specifies which {@code SqlSessionTemplate} to use in the case that there is more than one in the spring context.
* Usually this is only needed when you have more than one datasource.
Expand Down Expand Up @@ -364,6 +380,7 @@ public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
scanner.setAddToConfig(this.addToConfig);
scanner.setAnnotationClass(this.annotationClass);
scanner.setMarkerInterface(this.markerInterface);
scanner.setExcludeFilters(this.excludeFilters);
scanner.setSqlSessionFactory(this.sqlSessionFactory);
scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
Expand Down
116 changes: 116 additions & 0 deletions src/test/java/org/mybatis/spring/scan/filter/ScanFilterTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Copyright 2010-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.spring.scan.filter;

import com.mockrunner.mock.jdbc.MockDataSource;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.scan.filter.config.AppConfig;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import static org.assertj.core.api.Assertions.assertThat;

/**
* test the function of excludeFilters in @MapperScan
*/
public class ScanFilterTest {

private AnnotationConfigApplicationContext applicationContext;


@Test
void testCustomScanFilter() {
startContext(AppConfig.CustomFilterConfig.class);
// use org.mybatis.spring.scan.filter.datasource as basePackages and exclude package datasource2 by MapperScan.excludeFilters
// mapper in package datasource2 will not be registered to beanFactory
assertThat(applicationContext.containsBean("dataSource2Mapper")).isEqualTo(false);

// mapper in package datasource except datasource2 will be registered to beanFactory correctly.
assertThat(applicationContext.containsBean("commonDataSourceMapper")).isEqualTo(true);
assertThat(applicationContext.containsBean("dataSource1Mapper")).isEqualTo(true);
}

@Test
void testAnnoScanFilter() {
startContext(AppConfig.AnnoFilterConfig.class);

// use @AnnoTypeFilter to exclude mapper
assertThat(applicationContext.containsBean("annoExcludeMapper")).isEqualTo(false);

// mapper in package datasource except datasource2 will be registered to beanFactory correctly.
assertThat(applicationContext.containsBean("commonDataSourceMapper")).isEqualTo(true);
assertThat(applicationContext.containsBean("dataSource1Mapper")).isEqualTo(true);
assertThat(applicationContext.containsBean("dataSource2Mapper")).isEqualTo(true);
}


@Test
void testAssignableScanFilter() {
startContext(AppConfig.AssignableFilterConfig.class);

// exclude AssignableMapper by AssignableFilter
assertThat(applicationContext.containsBean("assignableMapper")).isEqualTo(false);

// mapper in package datasource except datasource2 will be registered to beanFactory correctly.
assertThat(applicationContext.containsBean("commonDataSourceMapper")).isEqualTo(true);
assertThat(applicationContext.containsBean("dataSource1Mapper")).isEqualTo(true);
assertThat(applicationContext.containsBean("dataSource2Mapper")).isEqualTo(true);
}

@Test
void testRegexScanFilter() {
startContext(AppConfig.RegexFilterConfig.class);

// exclude package datasource1 by Regex
assertThat(applicationContext.containsBean("dataSource1Mapper")).isEqualTo(false);

// mapper in package datasource except datasource1 will be registered to beanFactory correctly.
assertThat(applicationContext.containsBean("commonDataSourceMapper")).isEqualTo(true);
assertThat(applicationContext.containsBean("dataSource2Mapper")).isEqualTo(true);
}

@Test
void testAspectJScanFilter() {

startContext(AppConfig.AspectJFilterConfig.class);

// exclude dataSource1Mapper by AspectJ
assertThat(applicationContext.containsBean("dataSource1Mapper")).isEqualTo(false);

// mapper in package datasource except datasource1 will be registered to beanFactory correctly.
assertThat(applicationContext.containsBean("commonDataSourceMapper")).isEqualTo(true);
assertThat(applicationContext.containsBean("dataSource2Mapper")).isEqualTo(true);
}


private void startContext(Class<?> config) {
applicationContext = new AnnotationConfigApplicationContext();
// use @MapperScan with excludeFilters in AppConfig.class
applicationContext.register(config);
setupSqlSessionFactory("sqlSessionFactory");
applicationContext.refresh();
applicationContext.start();
}


private void setupSqlSessionFactory(String name) {
GenericBeanDefinition definition = new GenericBeanDefinition();
definition.setBeanClass(SqlSessionFactoryBean.class);
definition.getPropertyValues().add("dataSource", new MockDataSource());
applicationContext.registerBeanDefinition(name, definition);
}
}
Loading