【问题标题】:Getting error while working with configuring data source in spring boot在 Spring Boot 中配置数据源时出错
【发布时间】:2019-04-16 06:31:40
【问题描述】:

我想在一个 Spring Boot 应用程序中配置两个数据库,一开始我尝试使用一个,但出现错误。


@Configuration
public class DatabaseConfiguration {
    @Bean(name = "user")
    @ConfigurationProperties(prefix = "spring.user")
    public DataSource createProductServiceDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "jdbcuser")
    @Autowired
    public JdbcTemplate createJdbcTemplate_ProductService(@Qualifier("user") DataSource productServiceDS) {
        return new JdbcTemplate(productServiceDS);
    }
}
dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
spring.jpa.hibernate.ddl-auto=none
spring.user.url=jdbc:mysql://ip address:port/testdb
spring.user.username=username
spring.user.password=password
server.port=port
spring.user.driver-class-name=com.mysql.jdbc.Driver
@RestController
@Qualifier("jdbcuser")
public class Failed_Status {


    @Autowired
        JdbcTemplate jdbcTemplate;
    @GetMapping("/select")
    public List<User> getList()
    {
        String sql="select * from Customerinfo where status like 'F%'";
        List<User> u=new ArrayList<User>();

        u= jdbcTemplate.query(sql,new UserRowMapper());
        System.out.println(u);
        return u;


    }

}
Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded data source could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

由于我是 Spring Boot 新手,我无法找到如何使用多个数据库。请让我知道我需要做哪些更改才能成功运行该程序?

【问题讨论】:

    标签: java spring spring-boot jdbctemplate multiple-databases


    【解决方案1】:

    尝试使用@Primary 标记主要数据源,以便 JDBC 自动配置功能知道选择这个。当然,在使用多个数据源时,您自然需要这样做:

    @Bean(name = "user")
    @Primary
    @ConfigurationProperties(prefix = "spring.user")
    public DataSource createProductServiceDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean(name = "user2")
    @ConfigurationProperties(prefix = "spring.user2")
    public DataSource createProductServiceDataSource2() {
        return DataSourceBuilder.create().build();
    }
    

    【讨论】:

    • 仍然面临同样的问题
    • 尝试将主数据源上的前缀设为:spring.datasource.*
    • 当我使用批处理调度时,实现的 Job Launcher 类使用 Spring 数据源进行后台活动。因此我需要将我的数据源逻辑实现为辅助数据源。
    猜你喜欢
    • 2021-09-24
    • 2016-01-17
    • 2015-01-26
    • 2018-10-13
    • 2021-03-16
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多