user1578872
user1578872

Reputation: 9018

Spring Boot 2 - MySQL DataSource

I have the following properties in a Spring boot 2 application.

spring.datasource:
   username: user
   password: pwd
   driver-class-name: com.mysql.cj.jdbc.Driver
   url: jdbc:mysql://localhost:3306/test?enabledTLSProtocols=TLSv1.2&serverTimezone=UTC
   # Hikari CP
   type: com.zaxxer.hikari.HikariDataSource
   hikari.pool-name: ps-demo
   hikari.maximum-pool-size: 20
   hikari.max-lifetime: 1800000
   hikari.idle-timeout: 30000

Pom.xml,

I need mysql connector 5.1.38 for some reason.

<dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <optional>true</optional>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>

Unable to autowire,

@Named
public class MySqlDatasource {

    @Autowired
    private DataSource dataSource;

    public Connection getConnection() throws SQLException {
    
        return dataSource.getConnection();

    }
}

Error :-

"class": "org.springframework.beans.factory.NoSuchBeanDefinitionException",
    "msg": "No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}",
   

Is there anything wrong with the setup?

Upvotes: 0

Views: 465

Answers (1)

Damodar Hegde
Damodar Hegde

Reputation: 458

Do you have spring-boot-starter-jdbc in pom.xml?

Here's the dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Make sure you have the MySQL driver present as well.

Upvotes: 1

Related Questions