Beginner's Hack

復習用。誰かのためになれば...

Gradleプロジェクトでビルドエラー with SpringDataJPA

概要

Gradleプロジェクトをビルドした際に発生したエラーと対応についてまとめる。

事象

Spring Initializerで作成したGradleプロジェクトでビルドエラーが発生

# コンソール
$ gradlew build
:
:
略
:
:
> Task :test

DemoGApplicationTests > contextLoads() FAILED
    java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800
            Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658
                Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
                    Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException at DataSourceProperties.java:252

1 test completed, 1 failed
# /build/reports/tests/test/index.html

Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class

原因の推測

Spring Initializerでプロジェクトを作成した際に、Spring Data JPAを追加しているにも関わらず、 ドライバーの追加とapplication.propertiesの記載が抜けている。

対処

build.gradleにmysqlのドライバーの追加と、application.propertiesへの設定の追記を行なった。

# build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    runtimeOnly 'mysql:mysql-connector-java' # 追加
}

# application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://mysql/sample_schema
spring.datasource.username="自身の設定に合わせる"
spring.datasource.password="自身の設定に合わせる"
spring.jpa.database=”自身の設定に合わせる”

環境

  • docker