在Spring Boot中配置数据源时出错

时间:2019-04-16 06:31:41

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

我想在一个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的新手,所以找不到如何使用多个数据库。请让我知道成功运行程序需要做哪些更改?

1 个答案:

答案 0 :(得分:0)

尝试用@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();
}