Skip to content

Add 'scannable' option in @Component #29659

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
Expand All @@ -49,6 +50,7 @@
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationAttributesFilter;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
Expand Down Expand Up @@ -205,7 +207,7 @@ public void resetFilters(boolean useDefaultFilters) {
*/
@SuppressWarnings("unchecked")
protected void registerDefaultFilters() {
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
this.includeFilters.add(new AnnotationAttributesFilter(Component.class, Map.of("scannable", true)));
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
try {
this.includeFilters.add(new AnnotationTypeFilter(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,9 @@
*/
String value() default "";

/**
* return true if this component can be scanned.
*/
boolean scannable() default true;

}
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,6 @@
@AliasFor(annotation = Component.class)
String value() default "";

@AliasFor(annotation = Component.class, attribute = "scannable")
boolean scannable() default true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,7 @@
@AliasFor(annotation = Component.class)
String value() default "";

@AliasFor(annotation = Component.class, attribute = "scannable")
boolean scannable() default true;

}
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,6 @@
@AliasFor(annotation = Component.class)
String value() default "";

@AliasFor(annotation = Component.class, attribute = "scannable")
boolean scannable() default true;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2002-2012 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 example.scannable;

import org.springframework.stereotype.Controller;

/**
* @author Shen Feng
*/
@Controller(scannable = false)
public class UnscannableController {
}
26 changes: 26 additions & 0 deletions spring-context/src/test/java/example/scannable/UnscannableDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2002-2012 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 example.scannable;

import org.springframework.stereotype.Repository;

/**
* @author Shen Feng
*/
@Repository(scannable = false)
public class UnscannableDao {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2002-2012 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 example.scannable;

import org.springframework.stereotype.Service;

/**
* @author Shen Feng
*/
@Service(scannable = false)
public class UnscannableSerivce {
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
Expand Down Expand Up @@ -56,6 +57,7 @@
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.type.filter.AnnotationAttributesFilter;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
Expand Down Expand Up @@ -204,7 +206,7 @@ void customAnnotationTypeIncludeFilterWithIndex() {
}

private void testCustomAnnotationTypeIncludeFilter(ClassPathScanningCandidateComponentProvider provider) {
provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
provider.addIncludeFilter(new AnnotationAttributesFilter(Component.class, Map.of("scannable", true)));
testDefault(provider, false, false);
}

Expand Down Expand Up @@ -247,7 +249,7 @@ void customSupportedIncludeAndExcludeFilterWithIndex() {
}

private void testCustomSupportedIncludeAndExcludeFilter(ClassPathScanningCandidateComponentProvider provider) {
provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
provider.addIncludeFilter(new AnnotationAttributesFilter(Component.class, Map.of("scannable", true)));
provider.addExcludeFilter(new AnnotationTypeFilter(Service.class));
provider.addExcludeFilter(new AnnotationTypeFilter(Repository.class));
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
Expand Down Expand Up @@ -346,7 +348,7 @@ void withClassType() {
@Test
void withMultipleMatchingFilters() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
provider.addIncludeFilter(new AnnotationAttributesFilter(Component.class, Map.of("scannable", true)));
provider.addIncludeFilter(new AssignableTypeFilter(FooServiceImpl.class));
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
assertBeanTypes(candidates, NamedComponent.class, ServiceInvocationCounter.class, FooServiceImpl.class,
Expand All @@ -356,7 +358,7 @@ void withMultipleMatchingFilters() {
@Test
void excludeTakesPrecedence() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
provider.addIncludeFilter(new AnnotationAttributesFilter(Component.class, Map.of("scannable", true)));
provider.addIncludeFilter(new AssignableTypeFilter(FooServiceImpl.class));
provider.addExcludeFilter(new AssignableTypeFilter(FooService.class));
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,17 @@ public void withBasePackagesAndValueAlias() {
assertThat(ctx.containsBean("fooServiceImpl")).isTrue();
}

@Test
public void testScannableBean() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ComponentScanWithScannable.class);
ctx.refresh();
assertThat(ctx.containsBean("unscannableController")).isFalse();
assertThat(ctx.containsBean("unscannableSerivce")).isFalse();
assertThat(ctx.containsBean("unscannableDao")).isFalse();
assertThat(ctx.containsBean("fooServiceImpl")).isTrue();
}


@Configuration
@ComponentScan
Expand Down Expand Up @@ -461,4 +472,11 @@ class ComponentScanWithMultipleAnnotationIncludeFilters2 {}
basePackageClasses = example.scannable.PackageMarker.class)
class ComponentScanWithBasePackagesAndValueAlias {}

@ComponentScan(
value = "example.scannable")
class ComponentScanWithScannable{

}



Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public boolean match(MetadataReader metadataReader, MetadataReaderFactory metada
// Optimization to avoid creating ClassReader for superclass.
Boolean superClassMatch = matchSuperClass(superClassName);
if (superClassMatch != null) {
if (superClassMatch.booleanValue()) {
if (superClassMatch) {
return true;
}
}
Expand All @@ -99,7 +99,7 @@ public boolean match(MetadataReader metadataReader, MetadataReaderFactory metada
// Optimization to avoid creating ClassReader for superclass
Boolean interfaceMatch = matchInterface(ifc);
if (interfaceMatch != null) {
if (interfaceMatch.booleanValue()) {
if (interfaceMatch) {
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* Copyright 2002-2012 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.springframework.core.type.filter;

import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;


/**
* A {@link TypeFilter} which matches classes with a given annotation and attributes.
*
* @author Shen Feng
*/

public class AnnotationAttributesFilter extends AnnotationTypeFilter {

private final Map<String, Object> attributes;

public AnnotationAttributesFilter(Class<? extends Annotation> annotationType) {
super(annotationType);
this.attributes = Collections.emptyMap();
}

public AnnotationAttributesFilter(Class<? extends Annotation> annotationType, Map<String, Object> attributes) {
super(annotationType);
this.attributes = attributes;
}

public AnnotationAttributesFilter(Class<? extends Annotation> annotationType, boolean considerMetaAnnotations) {
super(annotationType, considerMetaAnnotations);
this.attributes = Collections.emptyMap();
}

public AnnotationAttributesFilter(Class<? extends Annotation> annotationType, Map<String, Object> attributes, boolean considerMetaAnnotations) {
super(annotationType, considerMetaAnnotations);
this.attributes = attributes;
}

public AnnotationAttributesFilter(Class<? extends Annotation> annotationType, boolean considerMetaAnnotations, boolean considerInterfaces) {
super(annotationType, considerMetaAnnotations, considerInterfaces);
this.attributes = Collections.emptyMap();
}

public AnnotationAttributesFilter(Class<? extends Annotation> annotationType, Map<String, Object> attributes, boolean considerMetaAnnotations, boolean considerInterfaces) {
super(annotationType, considerMetaAnnotations, considerInterfaces);
this.attributes = attributes;
}

@Override
protected boolean matchSelf(MetadataReader metadataReader) {
if (!super.matchSelf(metadataReader)) {
return false;
}
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();

Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(getAnnotationType().getName());
return matchAttributes(annotationAttributes);


}

private boolean matchAttributes(Map<String, Object> annotationAttributes) {
if (annotationAttributes == null) {
return false;
}
Set<String> keys = this.attributes.keySet();
for (String key : keys) {
Object value = annotationAttributes.get(key);
//use default value when value is null
value = value == null ? AnnotationUtils.getDefaultValue(getAnnotationType(), key) : value;
if (!Objects.equals(value, this.attributes.get(key))) {
return false;
}
}
return true;
}

@Override
protected Boolean matchSuperClass(String superClassName) {
return this.match(superClassName);
}

@Override
protected Boolean matchInterface(String interfaceName) {
return this.match(interfaceName);
}

@Nullable
protected Boolean match(String typeName) {
if (Object.class.getName().equals(typeName)) {
return false;
}
else if (typeName.startsWith("java")) {
if (!getAnnotationType().getName().startsWith("java")) {
// Standard Java types do not have non-standard annotations on them ->
// skip any load attempt, in particular for Java language interfaces.
return false;
}
try {
Class<?> clazz = ClassUtils.forName(typeName, getClass().getClassLoader());
Annotation annotation = this.considerMetaAnnotations ? AnnotationUtils.getAnnotation(clazz, getAnnotationType()) :
clazz.getAnnotation(getAnnotationType());
if (annotation == null) {
return false;
}
Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(annotation);
return matchAttributes(annotationAttributes);
}
catch (Throwable ex) {
// Class not regularly loadable - can't determine a match that way.
}

}
return null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class AnnotationTypeFilter extends AbstractTypeHierarchyTraversingFilter

private final Class<? extends Annotation> annotationType;

private final boolean considerMetaAnnotations;
protected final boolean considerMetaAnnotations;


/**
Expand Down
Loading