首页 > 解决方案 > Getting error while working with configuring data source in spring boot

问题描述

I want to configure two databases in one spring boot application & Initially I am trying with the one but getting an error.


@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).

As I am new to Spring boot I am unable to find how to work with multiple databases. Kindly let me know what changes I need to do to run the program successfully?

标签: javaspringspring-bootjdbctemplatemultiple-databases

解决方案


尝试使用标记主要数据源,@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();
}

推荐阅读