我终于成功实现了所有必要的过滤,这要感谢Josef的回答以及以下链接的帮助:
组件和服务可以配置为产生过滤器,因此我们可以同时指定目标服务和控制器并排除其他一切内容。
@ComponentScan(
basePackageClasses = {
MyTargetService.class,
MyTargetController.class
},
useDefaultFilters = false,
includeFilters = {
@ComponentScan.Filter(type = ASSIGNABLE_TYPE, value = MyTargetService.class),
@ComponentScan.Filter(type = ASSIGNABLE_TYPE, value = MyTargetController.class)
}
)
仓库。 这对于仓库来说不太可能起作用,但幸运的是@EnableJpaRepositories
支持相同类型的过滤器:
@EnableJpaRepositories(
basePackageClasses = {
MyTargetRepository.class
},
includeFilters = {
@ComponentScan.Filter(type = ASSIGNABLE_TYPE, value = MyTargetRepository.class)
}
)
实体类. 这部分比较棘手,因为 @EntityScan 不支持这些过滤器。虽然实体类没有引用 Spring bean,但我更喜欢仅加载测试所需的实体类。我没有找到任何支持过滤的实体类注解,但我们可以在 EntityManagerFactory
中使用 PersistenceUnitPostProcessor
以编程方式对它们进行过滤。以下是我的完整解决方案:
@Configuration
public class MyConfig {
private static String[] MODEL_PACKAGES = {
"com.full.path.to.entity.package1",
"com.full.path.to.entity.package2"
};
private static Set<String> TARGET_ENTITIES = new HashSet<>(Arrays.asList(
"com.full.path.to.entity.package1.MyTargetEntity1",
"com.full.path.to.entity.package2.MyTargetEntity2"
));
@Bean
public DataSource getDataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2).build();
}
@Bean
public EntityManagerFactory entityManagerFactory() {
ReflectionsPersistenceUnitPostProcessor reflectionsPersistenceUnitPostProcessor = new ReflectionsPersistenceUnitPostProcessor();
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(MODEL_PACKAGES);
factory.setDataSource(getDataSource());
factory.setPersistenceUnitPostProcessors(reflectionsPersistenceUnitPostProcessor);
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
public class ReflectionsPersistenceUnitPostProcessor implements PersistenceUnitPostProcessor {
@Override
public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
Reflections r = new Reflections("", new TypeAnnotationsScanner());
Set<Class<?>> entityClasses = r.getTypesAnnotatedWith(Entity.class, true);
Set<Class<?>> mappedSuperClasses = r.getTypesAnnotatedWith(MappedSuperclass.class, true);
pui.getManagedClassNames().clear();
for (Class<?> clzz : mappedSuperClasses) {
if (TARGET_ENTITIES.contains(clzz.getName())) {
pui.addManagedClassName(clzz.getName());
}
}
for (Class<?> clzz : entityClasses) {
if (TARGET_ENTITIES.contains(clzz.getName())) {
pui.addManagedClassName(clzz.getName());
}
}
}
}
}