Java 多数据源类型(属性/JNDI)配置

Java 多数据源类型(属性/JNDI)配置,java,jpa,spring-boot,Java,Jpa,Spring Boot,我有一个spring启动项目,它可以在独立模式(.jar和tomcat嵌入式)或wildfly服务器(.war)上运行。在独立模式下运行时,数据库配置应位于属性文件中。在wildfly中运行时,它从JNDI获取配置 问题是,当我重写工厂bean的bean定义时(因为我还不知道是否在独立/wildfly模式下运行),我如何回退到原始的工厂bean,以便spring boot能够从属性文件正确加载db配置 @Configuration @EnableJpaRepositories("server.r

我有一个spring启动项目,它可以在独立模式(.jar和tomcat嵌入式)或wildfly服务器(.war)上运行。在独立模式下运行时,数据库配置应位于属性文件中。在wildfly中运行时,它从JNDI获取配置

问题是,当我重写工厂bean的bean定义时(因为我还不知道是否在独立/wildfly模式下运行),我如何回退到原始的工厂bean,以便spring boot能够从属性文件正确加载db配置

@Configuration
@EnableJpaRepositories("server.repository")
@EntityScan(basePackages = {"server.domain"})
@EnableTransactionManagement
@Import(value = DataSourceAutoConfiguration.class)
public class GeneralDatabaseConfiguration {

    @Value("${spring.jpa.database")
    private String database;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        if (database == null) {
            //No database in properties file (wildfly mode)
            LocalContainerEntityManagerFactoryBean emfBean = new LocalContainerEntityManagerFactoryBean();
            emfBean.setDataSource(DataSourceLoader.getDataSource());
            emfBean.setPersistenceUnitName("testserver");
            emfBean.setJpaVendorAdapter(jpaVendorAdapter());
            emfBean.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE); // Caches only entities with @Cacheable-Annotation
            emfBean.setValidationMode(ValidationMode.NONE);
            return emfBean;
        } else {
            //Standalone mode - get DB config from file as usual
            return **???**
        }
    }

}

你正在使事情变得复杂。让Spring引导为您处理这个问题,它可以执行JPA或普通设置。对于单机版,在jar旁边的
应用程序.properties
中指定数据源。对于嵌入式,指定
spring.datasource.jndi名称,而不是其他
spring.datasource
属性。不需要覆盖任何内容。问题是,这个项目应该为许多客户提供相同的设置。因此,我们在属性文件中只有“mandant”编号。在DB中,我们有mandantNumber->JNDI名称(我已经将这个逻辑重写为“DataSourceLoader.getDataSource()”)。这就是为什么我不能简单地在属性文件中硬编码JNDI名称。在属性文件中,我只有mandant编号(但90%的客户的值为1)。
spring.datasource.jndi name=${spring.jpa.database}
应用程序wildfly.properties
或其他程序中,当您在wildfly上运行时启用该配置文件您不需要属性数据库,您只需创建一个单独的
应用程序.properties
并为客户端配置它,而不需要数据库。另外,我建议使用
PropertySource
从数据库加载属性,而不是创建一种自定义的加载属性的方法,这个
PropertySource
可以注册到
ApplicationContextInitializer
中,它可以与正常的属性支持一起工作。这比尝试解决问题容易得多。