W3docs

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

The error "Error creating bean with name 'dataSource' defined in class path resource" in Spring Boot typically indicates that there is a problem with the configuration of the dataSource bean.

The error "Error creating bean with name 'dataSource' defined in class path resource" in Spring Boot typically indicates that there is a problem with the configuration of the dataSource bean.

Here are a few possible causes for this error:

  1. The dataSource bean is defined multiple times in the configuration, which can cause a conflict.
  2. The dataSource bean depends on another bean that is not defined or not initialized properly.
  3. There is a typo in the bean name or the property name in the configuration.
  4. The required dependencies for the dataSource bean are not present on the classpath.

To troubleshoot this error, you can try the following:

  1. Verify that the dataSource bean is defined only once and check for conflicting @Bean methods or auto-configuration overlaps.
  2. Ensure all required dependencies (e.g., database drivers, connection pooling libraries like HikariCP) are present on the classpath.
  3. Check for spelling mistakes or typos in property names and bean definitions.
  4. Review the stack trace for the exact line causing the failure. For example, look for Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.datasource.url' to pinpoint missing properties.

If you are using a database connection pooling library such as HikariCP, make sure that the required library is present on the classpath and that the dataSource bean is properly configured.

Note: Spring Boot auto-configures a dataSource bean by default when a database driver is on the classpath. If you manually define a @Bean, ensure it does not conflict with auto-configuration (e.g., by using @ConditionalOnMissingBean or excluding the auto-configuration class).


@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

If you are still unable to resolve the issue, you can try adding debug log statements to the configuration to see what is causing the problem. You can also try starting the application with the --debug flag to enable debug logging.