简体   繁体   中英

Exclude autoconfiguration beans based on application yaml file

I have some beans that want to exclude from auto configurating based on a configuration on my application.yml file:

database:
  enabled: false

To do this, I created a Custom exclusion filter to exclude my beans from autoconfigurating:

public class DatabaseExclusionFilter implements AutoConfigurationImportFilter {

private static final Set<String> DATABASE_BEANS_SKIP = new HashSet<>(
        Arrays.asList("org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration",
                "org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration"));


@Value("${database.enabled}")
private boolean enabled;

@Override
public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {
    List<Boolean> excludeBeans = new ArrayList<>();
    if (!enabled) {
        excludeBeans = match(Arrays.asList(autoConfigurationClasses));
    }
    return convertToPrimitiveArray(excludeBeans);
}
}

This way, if the database is disabled in my project, I can exclude the configuration beans to being registered automatically. (This class is also indicated on the spring.factory file on the org.springframework.boot.autoconfigure.AutoConfigurationImportFilter).

This works fine but I have one problem, I cannot read the values from my yaml file, I think it is a precedence problem, maybe when the AutoConfigurationImportFilter is called, the @Value is not ready to work yet. How can I solve this?

Implement EnvironmentAware interface and get the property from the environment.

public class DatabaseExclusionFilter implements AutoConfigurationImportFilter, EnvironmentAware {

    private static final Set<String> DATABASE_BEANS_SKIP = new HashSet<>(
        Arrays.asList("org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration",
                "org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration"));

    private Environment environment;

    @Override
    public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {
        List<Boolean> excludeBeans = new ArrayList<>();
        if (!Boolean.parseBoolean(environment.getProperty("database.enabled")))) {
            excludeBeans = match(Arrays.asList(autoConfigurationClasses));
        }
        return convertToPrimitiveArray(excludeBeans);
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}

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