下面列出了怎么用org.springframework.core.type.filter.AssignableTypeFilter的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void afterPropertiesSet() throws Exception {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(GeminiException.class));
Set<BeanDefinition> components = provider.findCandidateComponents("it.at7.gemini");
for (BeanDefinition component : components) {
Class<?> gemException = Class.forName(component.getBeanClassName());
Class<?>[] innerClasses = gemException.getDeclaredClasses();
for (Class<?> innerClass : innerClasses) {
String simpleName = innerClass.getSimpleName();
if (simpleName.equals("Code")) {
Enum[] enumConstants = (Enum[]) innerClass.getEnumConstants();
register(enumConstants);
}
}
}
}
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaults() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(11, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertTrue(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaultsWithoutPostProcessors() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.setIncludeAnnotationConfig(false);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(6, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertTrue(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
@Test
public void testMultipleCustomExcludeFiltersAndDefaults() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(10, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertFalse(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaults() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(11, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertTrue(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaultsWithoutPostProcessors() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.setIncludeAnnotationConfig(false);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(6, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertTrue(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
@Test
public void testMultipleCustomExcludeFiltersAndDefaults() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(10, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertFalse(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
@PostConstruct
private void initializeCommandApi() {
logger.info("Initialising the command API list.");
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
BASE_COMMAND_CLASS.forEach(superCmdClazz -> provider.addIncludeFilter(new AssignableTypeFilter(superCmdClazz)));
List<String> commandClassNames = provider.findCandidateComponents(CORE_API_PACKAGE)
.stream()
.map(BeanDefinition::getBeanClassName)
.collect(Collectors.toList());
simpleToFullClassName = commandClassNames.stream().collect(Collectors.toMap(
this::simpleCommandClassName, commandClassName -> commandClassName
));
commandApi = commandClassNames.stream().collect(Collectors.toMap(
this::simpleCommandClassName, this::commandJsonSchema
));
logger.info("{} commands available.", commandApi.size());
}
@Test
public void testCompileExtendedServices() throws Exception
{
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
provider.addIncludeFilter(new AssignableTypeFilter(Extensible.class));
Set<BeanDefinition> components = provider.findCandidateComponents("org/alfresco/*");
Set<Class<? extends Extensible>> extensibles = new HashSet<>();
for (BeanDefinition component : components)
{
@SuppressWarnings("unchecked")
Class<? extends Extensible> extensibleClass = (Class<? extends Extensible>) Class.forName(component
.getBeanClassName());
extensibles.add(extensibleClass);
}
compile(extensibles);
}
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaults() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(11, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertTrue(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaultsWithoutPostProcessors() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.setIncludeAnnotationConfig(false);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(5, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertTrue(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertFalse(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
@Test
public void testMultipleCustomExcludeFiltersAndDefaults() {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class));
int beanCount = scanner.scan(BASE_PACKAGE);
assertEquals(10, beanCount);
assertFalse(context.containsBean("fooServiceImpl"));
assertFalse(context.containsBean("serviceInvocationCounter"));
assertTrue(context.containsBean("stubFooDao"));
assertTrue(context.containsBean("myNamedComponent"));
assertTrue(context.containsBean("myNamedDao"));
assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
@Override
public Set<Class<?>> getSubClasses(Class<?> clazz, String basePackage) {
ClassPathScanningCandidateComponentProvider provider =
new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(clazz));
Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
return components
.stream()
.map(
component -> {
try {
return Class.forName(component.getBeanClassName());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
String.format("Could not load child class '%s'.", component.getBeanClassName()),
e);
}
})
.collect(Collectors.toSet());
}
public static Map<String, CommandHandler> buildCommandHandlersRegistry(final String basePackage,
final ApplicationContext context) {
final Map<String, CommandHandler> registry = new HashMap<>();
final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
scanner.addIncludeFilter(new AssignableTypeFilter(CommandHandler.class));
CommandHandler currentHandler = null;
for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) {
currentHandler = (CommandHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()),
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
registry.put(currentHandler.getInterest(), currentHandler);
}
return registry;
}
public static Map<String, EventHandler> buildEventHandlersRegistry(final String basePackage,
final ApplicationContext context) {
final Map<String, EventHandler> registry = new HashMap<>();
final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
scanner.addIncludeFilter(new AssignableTypeFilter(EventHandler.class));
EventHandler currentHandler = null;
for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) {
currentHandler = (EventHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()),
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
registry.put(currentHandler.getInterest(), currentHandler);
}
return registry;
}
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
provider.addIncludeFilter(new AssignableTypeFilter(IdentifiableEntity.class));
Set<BeanDefinition> components = provider.findCandidateComponents(this.getClass().getPackage().getName());
List<Class<?>> classes = new ArrayList<>();
components.forEach(component -> {
try {
classes.add(Class.forName(component.getBeanClassName()));
} catch (Exception e) {
e.printStackTrace();
}
});
config.exposeIdsFor(classes.toArray(new Class[classes.size()]));
}
private void generateApiMessageGroovyClass(StringBuilder sb, List<String> basePkgs) {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
scanner.addIncludeFilter(new AssignableTypeFilter(APIMessage.class));
scanner.addIncludeFilter(new AssignableTypeFilter(APIReply.class));
scanner.addIncludeFilter(new AssignableTypeFilter(APIEvent.class));
scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
for (String pkg : basePkgs) {
for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
try {
Class<?> clazz = Class.forName(bd.getBeanClassName());
//classToApiMessageGroovyClass(sb, clazz);
classToApiMessageGroovyInformation(sb, clazz);
} catch (ClassNotFoundException e) {
logger.warn(String.format("Unable to generate groovy class for %s", bd.getBeanClassName()), e);
}
}
}
}
private void scanDeployer() {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
scanner.addIncludeFilter(new AssignableTypeFilter(AbstractDeployer.class));
scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
scanner.addExcludeFilter(new AnnotationTypeFilter(org.springframework.stereotype.Component.class));
for (BeanDefinition bd : scanner.findCandidateComponents("org.zstack.test")) {
try {
Class<?> clazz = Class.forName(bd.getBeanClassName());
AbstractDeployer d = (AbstractDeployer) clazz.newInstance();
deployers.put(d.getSupportedDeployerClassType(), d);
logger.debug(String.format("Scanned a deployer[%s] supporting %s", d.getClass().getName(), d.getSupportedDeployerClassType()));
} catch (Exception e) {
logger.warn(String.format("unable to create deployer[%s], it's probably there are some beans requried by deployer is not loaded, skip it. error message:\n%s", bd.getBeanClassName(), e.getMessage()));
}
}
}
void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Set<APIEvent> boundEvents = new HashSet<APIEvent>(100);
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
scanner.resetFilters(false);
scanner.addIncludeFilter(new AssignableTypeFilter(APIEvent.class));
for (String pkg : getBasePkgNames()) {
for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
Class<?> clazz = Class.forName(bd.getBeanClassName());
if (clazz == APIEvent.class) {
continue;
}
APIEvent evt = (APIEvent) clazz.newInstance();
boundEvents.add(evt);
}
}
for (APIEvent e : boundEvents) {
bus.subscribeEvent(this, e);
}
}
private Class<?>[] findSubTypes() {
List<Class<?>> types = new ArrayList<>();
if (this.packagesToScan != null) {
for (String pkg : this.packagesToScan) {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
false);
provider.addIncludeFilter(
new AssignableTypeFilter(RemoteApplicationEvent.class));
Set<BeanDefinition> components = provider.findCandidateComponents(pkg);
for (BeanDefinition component : components) {
try {
types.add(Class.forName(component.getBeanClassName()));
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Failed to scan classpath for remote event classes", e);
}
}
}
}
if (log.isDebugEnabled()) {
log.debug("Found sub types: " + types);
}
return types.toArray(new Class<?>[0]);
}
public void testWebServices() throws Exception {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(KfsKcSoapService.class));
Set<BeanDefinition> components = provider.findCandidateComponents(TEST_BASE_PACKAGE);
for (BeanDefinition component : components) {
String className = component.getBeanClassName();
Class<KfsKcSoapService> kfsServiceClass = (Class<KfsKcSoapService>) Class.forName(className);
try {
KfsKcSoapService kfsServiceInst = kfsServiceClass.newInstance();
URL myWsdl = kfsServiceInst.getWsdl();
assertTrue(isValidfetchXML(myWsdl));
}
catch (Exception ex) {
fail(ex.getMessage());
}
}
}
/**
* Search the classes in the PREDICATE_BASE_PACKAGE and build a list of all simple (non-composite) Predicate classes
* @return a list of simple Predicate classes
* @throws ClassNotFoundException
*/
private ArrayList<Class<?>> discoverSimplePredicateClasses() throws ClassNotFoundException {
ArrayList<Class<?>> discoveredPredicateClasses = new ArrayList<Class<?>>();
// This technique was copped from:
// http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
provider.addIncludeFilter(new AssignableTypeFilter(Predicate.class));
// scan in org.example.package
Set<BeanDefinition> components = provider.findCandidateComponents(PREDICATE_BASE_PACKAGE);
for (BeanDefinition component : components)
{
Class cls = Class.forName(component.getBeanClassName());
if (!cls.isMemberClass() // filter out inner class predicates from test packages
&& Predicate.class.isAssignableFrom(cls) // filter out any non-predicate classes
&& !CompositePredicate.class.isAssignableFrom(cls)) // filter out 'and' and 'or' predicates
{
discoveredPredicateClasses.add(cls);
// use class cls found
LOG.debug("discovered " + cls.toString());
}
}
return discoveredPredicateClasses;
}
@Test
public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(MaterialConfig.class));
Set<BeanDefinition> candidateComponents = provider.findCandidateComponents("com/thoughtworks");
List<Class> reflectionsSubTypesOf = candidateComponents.stream().map(beanDefinition -> beanDefinition.getBeanClassName()).map(s -> {
try {
return Class.forName(s);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
reflectionsSubTypesOf.removeIf(this::isNotAConcrete_NonTest_MaterialConfigImplementation);
List<Class> allExpectedMaterialConfigImplementations = allMaterialConfigsWhichAreDataPointsInThisTest();
assertThatAllMaterialConfigsInCodeAreTestedHere(reflectionsSubTypesOf, allExpectedMaterialConfigImplementations);
}
public static Set<Class<FunctionTransformation>> findFunctionTransformers(String basePackage) {
ClassPathScanner classPathScanner = new SimpleClassPathScanner(basePackage);
classPathScanner.addIncludeFilter(new AssignableTypeFilter(FunctionTransformation.class));
for(BeanDefinition bd : classPathScanner.findComponents()) {
try {
Class cl = Class.forName(bd.getBeanClassName());
if(!Modifier.isAbstract(cl.getModifiers())) {
logger.debug("Adding transformer function {}", cl);
functionTransformerClasses.add(cl);
} else {
logger.debug("Ignoring transformer function {}", cl);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return functionTransformerClasses;
}
@SuppressWarnings("unchecked")
public void scanEntities() {
synchronized ( entitiesScanPath ) {
for ( String path : entitiesScanPath ) {
ClassPathScanningCandidateComponentProvider provider =
new ClassPathScanningCandidateComponentProvider( true );
provider.addIncludeFilter( new AssignableTypeFilter( TypedEntity.class ) );
Set<BeanDefinition> components = provider.findCandidateComponents( path );
for ( BeanDefinition component : components ) {
try {
Class<?> cls = Class.forName( component.getBeanClassName() );
if ( Entity.class.isAssignableFrom( cls ) ) {
registerEntity( ( Class<? extends Entity> ) cls );
}
}
catch ( ClassNotFoundException e ) {
logger.error( "Unable to get entity class ", e );
}
}
registerEntity( DynamicEntity.class );
}
}
}
/**
* Determine if the specified include {@link TypeFilter} is supported by the index.
* @param filter the filter to check
* @return whether the index supports this include filter
* @since 5.0
* @see #extractStereotype(TypeFilter)
*/
private boolean indexSupportsIncludeFilter(TypeFilter filter) {
if (filter instanceof AnnotationTypeFilter) {
Class<? extends Annotation> annotation = ((AnnotationTypeFilter) filter).getAnnotationType();
return (AnnotationUtils.isAnnotationDeclaredLocally(Indexed.class, annotation) ||
annotation.getName().startsWith("javax."));
}
if (filter instanceof AssignableTypeFilter) {
Class<?> target = ((AssignableTypeFilter) filter).getTargetType();
return AnnotationUtils.isAnnotationDeclaredLocally(Indexed.class, target);
}
return false;
}
/**
* Extract the stereotype to use for the specified compatible filter.
* @param filter the filter to handle
* @return the stereotype in the index matching this filter
* @since 5.0
* @see #indexSupportsIncludeFilter(TypeFilter)
*/
@Nullable
private String extractStereotype(TypeFilter filter) {
if (filter instanceof AnnotationTypeFilter) {
return ((AnnotationTypeFilter) filter).getAnnotationType().getName();
}
if (filter instanceof AssignableTypeFilter) {
return ((AssignableTypeFilter) filter).getTargetType().getName();
}
return null;
}
@SuppressWarnings("unchecked")
protected TypeFilter createTypeFilter(Element element, @Nullable ClassLoader classLoader,
ParserContext parserContext) throws ClassNotFoundException {
String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE);
String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE);
expression = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(expression);
if ("annotation".equals(filterType)) {
return new AnnotationTypeFilter((Class<Annotation>) ClassUtils.forName(expression, classLoader));
}
else if ("assignable".equals(filterType)) {
return new AssignableTypeFilter(ClassUtils.forName(expression, classLoader));
}
else if ("aspectj".equals(filterType)) {
return new AspectJTypeFilter(expression, classLoader);
}
else if ("regex".equals(filterType)) {
return new RegexPatternTypeFilter(Pattern.compile(expression));
}
else if ("custom".equals(filterType)) {
Class<?> filterClass = ClassUtils.forName(expression, classLoader);
if (!TypeFilter.class.isAssignableFrom(filterClass)) {
throw new IllegalArgumentException(
"Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
}
return (TypeFilter) BeanUtils.instantiateClass(filterClass);
}
else {
throw new IllegalArgumentException("Unsupported filter type: " + filterType);
}
}
private void testCustomAssignableTypeIncludeFilter(ClassPathScanningCandidateComponentProvider provider,
Class<? extends BeanDefinition> expectedBeanDefinitionType) {
provider.addIncludeFilter(new AssignableTypeFilter(FooService.class));
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
// Interfaces/Abstract class are filtered out automatically.
assertTrue(containsBeanClass(candidates, AutowiredQualifierFooService.class));
assertTrue(containsBeanClass(candidates, FooServiceImpl.class));
assertTrue(containsBeanClass(candidates, ScopedProxyTestBean.class));
assertEquals(3, candidates.size());
assertBeanDefinitionType(candidates, expectedBeanDefinitionType);
}
@Test
public void customNotSupportedIncludeFilterUseScan() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.setResourceLoader(new DefaultResourceLoader(TEST_BASE_CLASSLOADER));
provider.addIncludeFilter(new AssignableTypeFilter(FooDao.class));
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
assertTrue(containsBeanClass(candidates, StubFooDao.class));
assertEquals(1, candidates.size());
assertBeanDefinitionType(candidates, ScannedGenericBeanDefinition.class);
}