在运行时创建Spring Boot数据源连接

时间:2019-07-22 18:26:47

标签: spring-boot hikaricp

我有一个使用GetMapping来获取配置信息的REST API。当您在运行时单击GetMapping方法时,我想创建一个新的数据源连接。所以基本上我想将一些参数传递到我定义的GetDataSource2方法中。我这样做正确吗?看起来我能够将参数传递给该方法,但不确定是否正在创建连接。它在方法中打印出消息(“使用第二个数据源”),但我无法获得任何连接详细信息(即:用户名,密码)。它只是说它们为空。如何通过传入参数创建连接?

SupportConfig.java

@Configuration
public class SupportConfig extends HikariConfig {

    @Bean
    @Primary
    public DataSource getDataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        dataSourceBuilder.url("jdbc:sqlserver://server\\QA:port;databaseName=dbName");
        dataSourceBuilder.username("QA");
        dataSourceBuilder.password("QApassword!");
        System.out.println("using the first data source");
        return dataSourceBuilder.build();
    }


    public DataSource getDataSource2(String driver, String url) {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();    
        dataSourceBuilder.driverClassName(driver);
        dataSourceBuilder.url(url);
        dataSourceBuilder.username("QA");
        dataSourceBuilder.password("QApassword");

        System.out.println("using the second data source");
        return dataSourceBuilder.build();
    }
}

DatabaseConfigController.java

@RestController
@RequestMapping("/api/")
public class DatabaseConfigController  {

    private SupportConfig supportConfig;

    @Autowired
    private DatabaseConfigRepository DatabaseConfigRepository;

    @GetMapping("/DatabaseConfig")
    public Iterable<DatabaseConfig> retrieveDatabaseConfig() {


        supportConfig = new SupportConfig();
        supportConfig.getDataSource2("com.microsoft.sqlserver.jdbc.SQLServerDriver", "jdbc:sqlserver://server\\QA:port;databaseName=dbName");
        //supportConfig.getDataSource();

        System.out.println("Username is " + supportConfig.getUsername());

        Iterable<DatabaseConfig> DatabaseConfig = DatabaseConfigRepository.findAll();
        return DatabaseConfig;

    }

0 个答案:

没有答案