Java 在实体上使用@ConditionalOnProperty的(变通方法)
我们有一个带有一些数据库实体类的Spring启动应用程序 我们使用ddl自动:验证来确保连接的数据库具有正确的模式 现在我们正在添加一个能够匹配不同环境的功能,NewFeatureService用Java 在实体上使用@ConditionalOnProperty的(变通方法),java,spring,hibernate,spring-boot,entity,Java,Spring,Hibernate,Spring Boot,Entity,我们有一个带有一些数据库实体类的Spring启动应用程序 我们使用ddl自动:验证来确保连接的数据库具有正确的模式 现在我们正在添加一个能够匹配不同环境的功能,NewFeatureService用@ConditionalOnProperty(“newfeature.enabled”)注释 在这里之前一切都很好 问题是该功能需要一个数据库实体 @Entity @ConditionalOnProperty("newfeature.enabled") // <--- doesn't work
@ConditionalOnProperty(“newfeature.enabled”)
注释
在这里之前一切都很好
问题是该功能需要一个数据库实体
@Entity
@ConditionalOnProperty("newfeature.enabled") // <--- doesn't work
public class NewFeatureEnitity{...}
@实体
“条件”属性(“NealFask.Fabelabl”)//Hibernate将把每个类看作一个实体,只要类/包包含在Hibernate设置中。
但是,Spring提供了方便(且简单)的解决方案,所以正如您所提到的,您可以使用@ConditionalOnProperty(我假设您使用的是Spring的java配置):
在Hibernate配置类中:
@Configuration
......
public class HibernateConfig {
@Bean
@ConditionalOnProperty(name = "newfeature.enabled")
public String newFeaturePackageToScan(){
return "com.example.so.entity.newfeature";
}
@Bean
public String commonPackageToScan(){
return "com.example.so.entity.common";
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Autowired DataSource dataSource, @Autowired String[] packagesToScan){
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
Properties jpaProperties = new Properties();
jpaProperties.put(AvailableSettings.HBM2DDL_AUTO, "validate");
jpaProperties.put(...); // other properties
emf.setDataSource(dataSource);
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
emf.setJpaProperties(jpaProperties);
emf.setPackagesToScan(packagesToScan);
return emf;
}
...
}
@Autowired String[]packagesToScan
将组合此数组中所有已定义的String bean(我假设您没有定义任何其他String bean),因此您可以为其他功能添加尽可能多的String bean,您可以查看更多详细信息
关键是要将newfeature包与common包分开,使common包不是父包。为了确保它不受监管,我想提供我的建议作为答案
它对spring boot的使用比提供的答案多一点
您可以将spring boot应用程序配置为仅扫描核心实体,如下所示:
@SpringBootApplication
@EntityScan("my.application.core")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
因此,您可以在诸如my.application.features
之类的包中提供可选实体(和功能)(可以随意使用任何其他结构,但可以使用先前指定的基本包之外的包)
也许您可以使用@EntityScan来设置默认情况下应该添加的实体包,并将@EntityScan(“可选的.entities”)添加到用@Conditional注释的配置类中?但这感觉有点难看:/看看org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor
。这可能是一个起点…如何设置hibernate来扫描实体?这不是我的@EntityScan建议基本上就是这么做的,但需要更多的代码吗?AFAIK,只有在依赖spring boot自动配置来定义EntityManager
时才使用,我也尝试回答没有自动配置。
@ConditionalOnProperty("newfeature.enabled")
@Configuration
@EntityScan("my.application.features.thefeature")
public class MyFeatureConfiguration {
/*
* No Configuration needed for scanning of entities.
* Do here whatever else should be configured for this feature.
*/
}