简体   繁体   中英

How to exclude scanning of beans that annotated with specific annotation and not annotated with another annotation?

In our WebApplication class we're using SpringBoot, so we're getting the default ComponentScan, but I want to exclude specific beans from this scan. I want to exclude all beans that (annotated with @Configuration ) AND ( not annotated with @ConditionalOnWebApplication ). I tried:

@SpringBootApplication
@ComponentScan(basePackages = { "com.yevgeny"} , includeFilters = {@ComponentScan.Filter(value = ConditionalOnWebApplication.class)} , excludeFilters = {@ComponentScan.Filter(value = Configuration.class)})
public class WebApplication extends SpringBootServletInitializer implements WebApplicationInitializer {...}

But it didn't scan the classes that have the both annotations. How can I achieve the requeired result?

You can create custom filters by implementing org.springframework.core.type.filter.TypeFilter

public class CustomFilter implements TypeFilter {

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
        throws IOException {
        Set<String> annotations = metadataReader.getAnnotationMetadata().getAnnotationTypes();

        return annotations.contains(Configuration.class.getName())
            && !annotations.contains(ConditionalOnWebApplication.class.getName());
    }

}

and then end up with something like this

@SpringBootApplication
@ComponentScan(includeFilters = @Filter(type=FilterType.CUSTOM, value=CustomFilter.class))
public class WebApplication extends SpringBootServletInitializer implements WebApplicationInitializer {...}

I didn't actually test any of this, but it seems like a step in the right direction.

Your excludeFilters will exclude all classes annotated with Configuration, regardless of what your includeFilters have. Your best approach will be to create a marker interface and add it the classes you want included, set this to the includeFilters in your ComponentScan. The ComponentScan will then only include these classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM