SpringBoot--排除指定的bean--方法/实例

简介

本文介绍SpringBoot如何排除某个指定的类(不将它扫描到容器中)。

本文说的这种情况是排除本来使用@Component等加入容器的类。如果想要排除自动配置(即:自定义starter,通过spring.factories来指定的配置类),见此文:SpringBoot--排除自动配置类--方法/实例_IT利刃出鞘的博客-CSDN博客

使用 RuoYi(若依)源码,不想用 RuoYi 自带的权限管理(ShiroConfig) ,但是不删除它,只是不让它生效。

方案1:@ComponentScan

@ComponentScan(excludeFilters = 
    {@ComponentScan.Filter(
        type = FilterType.REGEX, 
        pattern = {com.ruoyi.framework.config.ShiroConfig"})})
@SpringBootConfiguration
public class RuoYiApplication {

1.在@ComponentScan 中指定 excludeFilters 属性。该属性指定排除的Bean/类。
2.使用正则表达式方式(FilterType.REGEX)排除类 "com.ruoyi.framework.config.ShiroConfig"

方案2:@ComponentScans

@ComponentScans说明

@ComponentScans由所有的@ComponentScan组成,每个 @ComponentScan 都会影响 @ComponentScans。

自定义@ComponentScans的方法

@Configuration
@EnableAutoConfiguration
@ComponentScans({
    @ComponentScan(
            basePackages = {"com.ruoyi"}, 
            excludeFilters = {
                    @Filter(type = FilterType.REGEX, pattern = {
                            "com.ruoyi.framework.config.ShiroConfig"})}),
    @ComponentScan(basePackages = {"com.third.package"}),
public class RuoYiApplication {

@ComponentScan.Filter详解

可以看到,上边都是用了一个注解:@ComponentScan.Filter。

@ComponentScan(excludeFilters = {
    @ComponentScan.Filter(
        type = FilterType.ASSIGNABLE_TYPE, 
        value = {Xxx.class, Yyy.class})})

上边这段代码的含义:Xxx和Yyy这两个类不会作为bean加入容器(即使它们类上标注了@Component等)。

@ComponentScan.Filter源码

package org.springframework.context.annotation;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
    // 其他
    Filter[] includeFilters() default {};
    Filter[] excludeFilters() default {};
    @Retention(RetentionPolicy.RUNTIME)
    @Target({})
    @interface Filter {
        FilterType type() default FilterType.ANNOTATION;
        @AliasFor("classes")
        Class<?>[] value() default {};
        @AliasFor("value")
        Class<?>[] classes() default {};
        String[] pattern() default {};

FilterType

package org.springframework.context.annotation;
public enum FilterType {
    ANNOTATION,
    ASSIGNABLE_TYPE,
    ASPECTJ,
    REGEX,
    CUSTOM

1.ANNOTATION:注解类型
表示:加了指定的注解的类不加入容器。
例:(下边Xxx和Yyy都是注解类)
excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {Xxx.class, Yyy.class})}

2.ASSIGNABLE_TYPE:指定类型
含义:指定的类不作为bean加入容器。
例:(下边Xxx和Yyy都是注解类)
excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {Xxx.class, Yyy.class})}

3.ASPECTJ:按照Aspectj表达式
含义:符合指定Aspectj表达式的类不加入容器。

4.REGEX:按照正则表达式
含义:符合指定正则表达式的类不加入容器。
excludeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = {"com.example.", "com.abc.def."})}

5.CUSTOM:自定义规则

可使用多个