Spring Boot: не удалось настроить источник данных: атрибут «url» не указан, и встроенный источник данных не может быть настроен

Следующая ошибка возникает, когда я запускаю свое веб-приложение.

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class

Описание выброшенной ошибки выглядит следующим образом:

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


    Action:

    Consider the following:<br>
        If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
<br>    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

После ссылки на этот ответ я знаю, что должен внести некоторые изменения в свой файл pom.xml. Но я не знаю, что изменить, и даже подобные вопросы на StackOverflow не могли помочь мне разобраться.

Мой pom.xml выглядит следующим образом (при создании проекта я добавил зависимости «Web», «JPA», «MySQL»),

    <?xml version = "1.0" encoding = "UTF-8"?>
    <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.3.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>SL2INDUSTRY</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>SL2INDUSTRY</name>
        <description>Demo project for Spring Boot</description>

        <properties>
            <java.version>1.8</java.version>
        </properties>

        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-jasper -->
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <scope>provided</scope>
            </dependency>

            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-tomcat -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <version>2.1.3.RELEASE</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
            <dependency>
                <groupId>com.fasterxml.jackson.dataformat</groupId>
                <artifactId>jackson-dataformat-xml</artifactId>
                <version>2.9.8</version>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>

    </project>

Plese note that I don't need to deal with H2 databases in this situation so H2 is not a solution for me.

Редактирует: application.properties файл

spring.mvc.view.suffix=.jsp

Вы можете добавить содержимое файла application.properties, о котором идет речь.

dkb 02.04.2019 21:53
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
3
1
34 479
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Для этого есть несколько возможностей, но в первый раз нужно сделать три вещи.

1 - Конкретные совместимые версии ваших зависимостей от вашего pom.xml

2 - Вам нужно добавить базу данных driverConnector на pom.xml

3. Создайте файл application.properties в каталоге «src/main/resources/application.properties» и поместите туда свою конфигурацию базы данных.

application.properties (ПРИМЕЧАНИЕ. Измените значения de в конфигурации вашей базы данных)

spring.jpa.hibernate.ddl-auto=create

spring.datasource.url=jdbc:mysql://localhost:3306/db_example

spring.datasource.username=user

spring.datasource.password=ThePassword

вы можете проверить шаблон здесь: https://spring.io/guides/gs/accessing-data-mysql/

Причиной ошибки является зависимость MySQL, которая выбрана мной при создании проекта.

INDRAJITH 02.04.2019 21:09

Если я не выберу его, проект работает правильно. Но проблема в том, что мне нужно использовать MySQL.

INDRAJITH 02.04.2019 21:09

Возможно, у вас есть конфликт между зависимостями, попробуйте удалить зависимость tomcat-embed-jasper, вам это не нужно для использования tomcat, достаточно spring-boot-starter-tomcat. Если проблема не устранена, поделитесь файлами application-spring-boot.java и application.properties.

Eder Rodrigues 02.04.2019 22:37

Еще раз проверьте мой ответ выше, я отредактировал свойства spring.datasources, которые вам нужно добавить в свои application.properties.

Eder Rodrigues 03.04.2019 16:46
Ответ принят как подходящий

Если вы читаете свой след ошибки:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class

Вы заметите, что он пытается использовать источник данных hikari для настройки соединения с bd. В чем дело?

Вы используете весеннюю загрузку 2. И в этой версии весенней загрузки изменилась конфигурация по умолчанию.

Как вы можете видеть по этому адресу:

https://www.baeldung.com/spring-boot-hikari#spring-boot-2

In Spring Boot 2, Hikari is the default DataSource implementation.

This is what’s changed from Spring Boot 1.x:

· the dependency to Hikari is now automatically included in spring-boot-starter-data-jpa

· the discovery algorithm that automatically determines a DataSource implementation now prefers Hikari over TomcatJDBC (see the reference manual).

Thus, we have nothing to do if we want to use Hikari in an application based on Spring Boot 2.x.

И комплектация Hikari другая.

Затем я предполагаю, что вы хотите использовать пул соединений tomcat. Вы можете сделать:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
    <version>9.0.10</version>
</dependency>

This will exclude Hikari by default from your spring jpa configuration and then you will need tomcat-jdbc. The you can configure de datasource:

This simple approach allows us to get Spring Boot using a Tomcat connection pool without having to write a @Configuration class and programmatically define a DataSource bean.

It’s also worth noting that in this case, we’re using the H2 in-memory database. Spring Boot will autoconfigure H2 for us, without having to specify a database URL, user, and password.

We just need to include the corresponding dependency in the “pom.xml” file and Spring Boot will do the rest for us.

Alternatively, it’s possible to skip the connection pool scanning algorithm that Spring Boot uses and explicitly specify a connection pooling datasource in the “application.properties” file, using the “spring.datasource.type” property:

spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
// other spring datasource properties
spring.datasource.url=...
spring.datasource.username=...
spring.datasource.password=...
...

Здесь у вас есть полный справочник по отключению Hikari и настройке tomcat:

https://www.baeldung.com/spring-boot-tomcat-connection-pool

Если вы хотите использовать Hikari, конфигурация будет другой:

https://www.baeldung.com/spring-boot-hikari

Но один из этих двух вариантов решит вашу проблему.

Другие вопросы по теме