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
you can exclude then via
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}))
but you could exclude them in your @Configuration
by adding
@EnableAutoConfiguration(exclude= {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
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<String> 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.