Spring Boot 在运行时更改数据源和 JPA 属性

我正在编写一个桌面Spring Boot和Data-JPA应用程序。
初始设置来自(一些和)
我的程序的一个功能是通过ui指定数据库设置(rdbms类型,主机,端口,用户名,密码等)。
这就是为什么我想在运行时重新定义已经初始化的数据库属性。这就是为什么我正在寻找一种方法来做到这一点。application.propertiesspring.datasource.*spring.jpa.*

我试图做以下事情:
1)我编写了自定义DbConfig,其中bean在Singleton Scope中声明。DataSource

@Configuration
public class DBConfig {

  @ConfigurationProperties(prefix = "spring.datasource")
  @Bean
  @Scope("singleton")
  @Primary
  public DataSource dataSource() {
    return DataSourceBuilder
            .create()
            .build();
  }

}

2)在一些DBSettingsController中,我得到了这个bean的实例并更新了新的设置:

public class DBSettingsController {
   ...
   @Autowired DataSource dataSource;
   ...

   public void applySettings(){

       if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource){
        org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource = (org.apache.tomcat.jdbc.pool.DataSource) dataSource;
        PoolConfiguration poolProperties = tomcatDataSource.getPoolProperties();
        poolProperties.setUrl("new url");
        poolProperties.setDriverClassName("new driver class name");
        poolProperties.setUsername("new username");
        poolProperties.setPassword("new password");
       }
   }
}

但它没有任何效果。Spring Data Repositories是使用初始初始化的DataSource属性的钢制。

我也听说过Spring Cloud Config@RefreshScope。但我认为在我的小型桌面应用程序旁边运行http Web服务器是一种开销。

是否可以为此类 Bean 编写自定义作用域?或者以某种方式绑定对 bean 属性和相应的 bean 属性进行更改?application.properties


答案 1

这是我的解决方案(它可能是在2016th创建的:它可能已经过时了):

DbConfig(它不是真的需要,我只是添加了完整性配置)

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.sql.DataSource;


@Configuration
public class DBConfig extends HibernateJpaAutoConfiguration {

    @Value("${spring.jpa.orm}")
    private String orm; // this is need for my entities declared in orm.xml located in resources directory


    @SuppressWarnings("SpringJavaAutowiringInspection")
    public DBConfig(DataSource dataSource, JpaProperties jpaProperties, ObjectProvider<JtaTransactionManager> jtaTransactionManagerProvider) {
        super(dataSource, jpaProperties, jtaTransactionManagerProvider);

    }

    @Override
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            EntityManagerFactoryBuilder factoryBuilder)
    {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = super.entityManagerFactory(factoryBuilder);
        entityManagerFactoryBean.setMappingResources(orm);
        return entityManagerFactoryBean;
    }
}

数据源配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

    @Bean
    @Qualifier("default")
    @ConfigurationProperties(prefix = "spring.datasource")
    protected DataSource defaultDataSource(){
        return DataSourceBuilder
                .create()
                .build();
    }

    @Bean
    @Primary
    @Scope("singleton")
    public AbstractRoutingDataSource routingDataSource(@Autowired @Qualifier("default") DataSource defaultDataSource){
        RoutingDataSource routingDataSource = new RoutingDataSource();
        routingDataSource.addDataSource(RoutingDataSource.DEFAULT,defaultDataSource);
        routingDataSource.setDefaultTargetDataSource(defaultDataSource);
        return routingDataSource;
    }
}

我的路由数据源扩展:

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


public class RoutingDataSource extends AbstractRoutingDataSource {

    static final int DEFAULT = 0;
    static final int NEW = 1;

    private volatile int key = DEFAULT;

    void setKey(int key){
        this.key = key;
    }

    private Map<Object,Object> dataSources = new HashMap();

    RoutingDataSource() {
        setTargetDataSources(dataSources);
    }

    void addDataSource(int key, DataSource dataSource){
        dataSources.put(new Integer(key),dataSource);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return new Integer(key);
    }

    @Override
    protected DataSource determineTargetDataSource() {
        return (DataSource) dataSources.get(key);
    }
}

这里是特殊的弹簧组件,用于在运行时切换数据源:

import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
public class DBSettingsSwitcher {

    @Autowired
    private AbstractRoutingDataSource routingDataSource;

    @Value("${spring.jpa.orm}")
    private String ormMapping;

    public void applySettings(DBSettings dbSettings){

        if (routingDataSource instanceof RoutingDataSource){
            // by default Spring uses DataSource from apache tomcat

            DataSource dataSource = DataSourceBuilder
                    .create()
                    .username(dbSettings.getUserName())
                    .password(dbSettings.getPassword())
                    .url(dbSettings.JDBConnectionURL())
                    .driverClassName(dbSettings.driverClassName())
                    .build();

            RoutingDataSource rds = (RoutingDataSource)routingDataSource;

            rds.addDataSource(RoutingDataSource.NEW,dataSource);
            rds.setKey(RoutingDataSource.NEW);

            updateDDL(dbSettings);
        }
    }

    private void updateDDL(DBSettings dbSettings){

        /** worked on hibernate 5*/
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .applySetting("hibernate.connection.url", dbSettings.JDBConnectionURL())
                .applySetting("hibernate.connection.username", dbSettings.getUserName())
                .applySetting("hibernate.connection.password", dbSettings.getPassword())
                .applySetting("hibernate.connection.driver_class", dbSettings.driverClassName())
                .applySetting("hibernate.dialect", dbSettings.dialect())
                .applySetting("show.sql", "false")
                .build();

        Metadata metadata = new MetadataSources()
                .addResource(ormMapping)
                .addPackage("specify_here_your_package_with_entities")
                .getMetadataBuilder(registry)
                .build();

        new SchemaUpdate((MetadataImplementor) metadata).execute(false,true);
    }
}

其中数据库设置只是一个接口(您应该根据需要实现它):

public interface DBSettings {

    int getPort();

    String getServer();

    String getSelectedDataBaseName();

    String getPassword();

    String getUserName();

    String dbmsType();

    String JDBConnectionURL();

    String driverClassName();

    String dialect();
}

在Spring上下文中拥有自己的DBSettings实现和构建的DBSettingsSwitcher,现在您只需调用即可,您的数据请求将被路由到新的数据源。DBSettingsSwitcher.applySettings(dbSettingsIml)


答案 2

推荐