Is it possible to disable an autoconfiguration class from another autoconfiguration class in spring boot?

后端 未结 2 2198
后悔当初
后悔当初 2021-02-15 12:22

I\'m working on a data access library and would like to be able to include it as a dependency in other projects with minimal configuration (ideally just autowire a repo). In par

2条回答
  •  -上瘾入骨i
    2021-02-15 13:15

    There's a very handy interface called AutoConfigurationImportFilter, which decides on which auto-configuration should be loaded. This is also how @ConditionalOnClass annotation works.

    In your library, add the following class:

    public class MyExclusionFilter
            implements AutoConfigurationImportFilter {
    
        private static final Set SHOULD_SKIP = new HashSet<>(
                Arrays.asList("org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration",
                        "org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration"));
    
        @Override
        public boolean[] match(String[] classNames, AutoConfigurationMetadata metadata) {
            boolean[] matches = new boolean[classNames.length];
    
            for(int i = 0; i< classNames.length; i++) {
                matches[i] = !SHOULD_SKIP.contains(classNames[i]);
            }
            return matches;
        }
    }
    

    This class needs to be registered in spring.factories to work. Add the following line in the library into META-INF/spring.factories:

    org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=com.mycompany.db.MyExclusionFilter
    

    You don't need to make any changes to the dependent project. Just add the library as a dependency and the auto-configuration you specified won't be loaded for the whole application.

    NOTE: You can add more than one import filter, only the auto-configuration classes not filtered in all import filters will get loaded.

    For details, see the source code of org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#filter and org.springframework.boot.autoconfigure.condition.OnClassCondition.java classes.

提交回复
热议问题