Tenho um projeto em SpringBoot conectando em um banco MySql 8.0.31 (WampServer 3.3.0).
O projeto estava apresentando o seguinte erro:
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-03-24T13:16:52.572-03:00 ERROR 5192 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
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:
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).
A partir daí eu inseri a seguinte anotação na minha classe “application”: @SpringBootApplication (exclude = {DataSourceAutoConfiguration.class }) e parou de apresentar o erro, mas não está criando as tabelas no banco.
Será que pode ter relação dessa anotação com a não criação das tabelas no banco?
Meu application.properties:
#Configurações do JPA:
spring.datasource.url=jdbc:mysql://localhost:3306/minas_cafe?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=359423
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=validate
#Porta de trabalho do Tomcat
server.port=${port:8080}
#Exibe os comandos SQL
spring.jpa.show-sql=true
#Especifica qual o banco de dados você usará
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#Enable spring data repos
spring.data.jpa.repositories.enabled=true
spring.jpa.database=mysql
package com.cafe.api;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
//Desabilitando a segurança do SpringBoot - Informa para o spring-boot excluir/desativar a autoconfiguração de DataSource
@SpringBootApplication (exclude = {DataSourceAutoConfiguration.class }/*, scanBasePackages= {"com.minascafe.api.repositories"}*/)
//@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) //tenta configurar automaticamente seu aplicativo Spring com base nas dependências jar que você adicionou
//E exclui o carregamento do bean da fonte de dados
//@EntityScan(basePackages = {"com.minascafe.api.entities"}) //Onde estão sendo criadas as classes Java mapeadas com @Entity
//@ComponentScan(basePackages = {"com.minascafe.api.repositories"})
// //@EnableJpaRepositories(basePackages = {"com.minascafe.api.repositories"})
public class MinasApplication {
public static void main(String[] args) {
SpringApplication.run(MinasApplication.class, args);
}
//gera um componente do Spring
@Bean
public CommandLineRunner commandLineRunner() { //Executa automaticamente junto com o Spring
return args ->{
System.out.println("Executando o primeiro teste do projeto perfeitamente!");
};
}
}
O problema com o dataSource pode ser algum bug na IDE já que vc já adicionou o driver ao pom.xml.
Por isso eu sugiro que vc de um clean no seu projeto e tente fazer o rebuild novamente.
Eu fiz um teste usando o seu pom.xml sem adicionar o driver do MySQL e deu o mesmo erro no dataSource, mas foi só eu adicionar o driver que este erro sumiu.
Nisso apareceu outro erro por causa da compatibilidade entre versões. Este erro eu corrigi removendo a seguinte dependência:
Se eu removo “(exclude = { DataSourceAutoConfiguration.class })” da anotação @SpringBootApplication, apresenta o seguinte erro:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.4)
2023-03-29T14:44:43.220-03:00 INFO 1948 --- [ restartedMain] com.cafe.api.MinasApplication : Starting MinasApplication using Java 17.0.6 with PID 1948 (C:\Users\Edson\Documents\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasCafe\target\classes started by Edson in C:\Users\Edson\Documents\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasCafe)
2023-03-29T14:44:43.235-03:00 INFO 1948 --- [ restartedMain] com.cafe.api.MinasApplication : No active profile set, falling back to 1 default profile: "default"
2023-03-29T14:44:43.327-03:00 INFO 1948 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2023-03-29T14:44:43.327-03:00 INFO 1948 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2023-03-29T14:44:44.431-03:00 INFO 1948 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-03-29T14:44:44.466-03:00 INFO 1948 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 20 ms. Found 0 JPA repository interfaces.
2023-03-29T14:44:45.279-03:00 INFO 1948 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-03-29T14:44:45.297-03:00 INFO 1948 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-03-29T14:44:45.297-03:00 INFO 1948 --- [ restartedMain] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-03-29T14:44:45.404-03:00 INFO 1948 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-03-29T14:44:45.404-03:00 INFO 1948 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2076 ms
2023-03-29T14:44:45.490-03:00 WARN 1948 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class
2023-03-29T14:44:45.495-03:00 INFO 1948 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2023-03-29T14:44:45.532-03:00 INFO 1948 --- [ restartedMain].s.b.a.l.ConditionEvaluationReportLogger :
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-03-29T14:44:45.577-03:00 ERROR 1948 --- [ restartedMain] .s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
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:
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).
Bem, eu removi a dependência do hibernate, dei um ‘clean’ no projeto. Mas, ao menos com esse ‘exclude’ na anotação @SpringBootApplication não cria as tabelas no banco. E se eu removo esse ‘exclude’, apresenta o erro mencionado acima.
Na realidade está dizendo que o atributo ‘url’ no datasource não está especificado, mas no meu application.properties está definido “spring.datasource.url=jdbc:mysql://localhost:3306/minas_cafe?createDatabaseIfNotExist”
The name of the class that implements java.sql.Driver in MySQL Connector/J has changed from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver. The old class name has been deprecated.
Pessoal, consegui resolver aqui. Vi em algum lugar que o Eclipse está apresentando esse problema com alguns desenvolvedores. Migrei meu projeto para o Intellij, dei uma repaginada no meu pom.xml e funcionou normalmente. Executou sem apresentar erros e criou as tabelas no banco de dados (MySql) conforme eu precisava.
Fiquei decepcionado com o Spring Tool Suite (Eclipse).