Failing to start my spring boot application due to 'javax.sql.DataSource' that could not be found - mysql

I am a beginner in spring boot and am trying to write a simple spring boot application.
My folder structure is as follows:
-> Project
-> build.gradle
-> settings.gradle
-> src/main/java
-> package
-> Main.java
-> UserController.java
-> UserRespository.java
-> dto
-> User.java
->src/main/resouces
-> application.properties
My build.gradle is as follows :
buildscript {
repositories {
jcenter()
}
dependencies {
classpath(
'org.springframework.boot:spring-boot-gradle- plugin:1.5.6.RELEASE'
)
classpath('mysql:mysql-connector-java:5.1.34')
}
}
apply plugin: 'java'
apply plugin: 'spring-boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile(
'org.springframework.boot:spring-boot-starter-actuator',
'org.springframework.boot:spring-boot-starter-web',
'org.springframework.boot:spring-boot-starter-data-jpa'
)
compile('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
The application.properties is as follows:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/user
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.database=MYSQL
spring.jpa.show-sql = true
My Main.java is as follows:-
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
#SpringBootApplication
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
};
}
I am able to successfully build the application. If I run the application , I get Unable to start application with the following stacktrace:
2017-08-14 20:43:02.976 WARN 27205 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2017-08-14 20:43:02.978 INFO 27205 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2017-08-14 20:43:03.007 INFO 27205 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-08-14 20:43:03.198 ERROR 27205 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration required a bean of type 'javax.sql.Data Source' that could not be found.
- Bean method 'dataSource' not loaded because #ConditionalOnProperty (spring.datasource.jndi-name) did not find property 'jndi-name'
- Bean method 'dataSource' not loaded because #ConditionalOnBean (types: org.springframework.boot.jta.XADataSourceWrapper; SearchStrategy: all) did not find any beans
Action:
Consider revisiting the conditions above or defining a bean of type 'javax.sql.DataSource' in your configuration.
I have checked the dependencies tree and can find both hibernate as well as mysql connector in it.
Have tried removing #EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) , in that case I get Cannot load driver class: com.mysql.jdbc.Driver

You should move the dto package inside into your Main.java class package, In your case it should be like src/main/java/package/dto
So when spring-boot scans, your entity will be visible to the scanner.
Make sure you have added the MySQL driver dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

Related

why the test container with the RabbitMQ is creates every time anew and is not shared between the tests

I have 4 tests for listeners, the application is built on SpringBoot and uses Testcontainers, I run mvn clean install, and I get the following:
9-08-15 18:37:01.287 INFO 8312 --- [tContainer#1-11] o.s.a.r.c.CachingConnectionFactory : Attempting to connect to: [localhost:33724]
[INFO]
[INFO] Results:
[INFO]
2019-08-15 18:37:01.288 ERROR 8312 --- [tContainer#1-11] o.s.a.r.l.SimpleMessageListenerContainer : Failed to check/redeclare auto-delete queue(s).
org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused (Connection refused)
at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:62)
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:509)
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:682)
at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.createConnection(ConnectionFactoryUtils.java:214)
at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:2073)
at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:2047)
at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:2027)
at org.springframework.amqp.rabbit.core.RabbitAdmin.getQueueProperties(RabbitAdmin.java:403)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.attemptDeclarations(AbstractMessageListenerContainer.java:1787)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.redeclareElementsIfNecessary(AbstractMessageListenerContainer.java:1768)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.initialize(SimpleMessageListenerContainer.java:1195)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1041)
at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
at java.base/java.net.Socket.connect(Socket.java:591)
at com.rabbitmq.client.impl.SocketFrameHandlerFactory.create(SocketFrameHandlerFactory.java:60)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1102)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1054)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:994)
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:462)
... 11 common frames omitted
I made an output to the log file of the mvn clean install command, and the above occurs throughout the entire log, many times, but this is not the main problem, the problem is that the container with RabbitMQ starts many times, I would like to share it between tests.
2019-08-15 18:35:26.126 INFO --- [ main] 🐳 [rabbitmq:3.7-management] : Creating container for image: rabbitmq:3.7-management
2019-08-15 18:35:54.665 INFO 8312 --- [ main] 🐳 [rabbitmq:3.7-management] : Creating container for image: rabbitmq:3.7-management
2019-08-15 18:36:15.510 INFO 8312 --- [ main] 🐳 [rabbitmq:3.7-management] : Creating container for image: rabbitmq:3.7-management
2019-08-15 18:36:31.862 INFO 8312 --- [ main] 🐳 [rabbitmq:3.7-management] : Creating container for image: rabbitmq:3.7-management
4 times, 4 listeners.
I tried using forkCount = 0 for maven-surefire-plugin and for maven-failsafe-plugin, this did not help.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<forkCount>0</forkCount>
</configuration>
</plugin>
#RunWith(SpringRunner.class)
#SpringBootTest(
value = {
"spring.cloud.discovery.enabled = false"
},
webEnvironment = RANDOM_PORT)
#ActiveProfiles(TEST_PROFILE)
public abstract class AbstractTest {
#LocalServerPort
private int port;
}
#ContextConfiguration(initializers = AbstractRabbitTest.Initializer.class)
public abstract class AbstractRabbitTest extends AbstractTest {
#ClassRule
public static RabbitMQContainer rabbitMQContainer = new RabbitMQContainer("rabbitmq:3.7-management")
.withExposedPorts(5672)
.withVhost("/")
.withUser("admin", "admin")
.withPermission("/", "admin", ".*", ".*", ".*");
public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
#Override
public void initialize(ConfigurableApplicationContext applicationContext) {
TestPropertyValues values = TestPropertyValues.of(
"spring.rabbitmq.host=" + rabbitMQContainer.getContainerIpAddress(),
"spring.rabbitmq.port=" + rabbitMQContainer.getMappedPort(5672),
"spring.rabbitmq.username=admin",
"spring.rabbitmq.password=admin"
);
values.applyTo(applicationContext);
}
}
}
Every my test looks like this and uses spring-amqp:
public class CloseProcessListenerTest extends AbstractRabbitTest {
ClassRule in JUnit will execute the rule per class, not per "suite". Since you have multiple test classes that extend it, you start multiple containers during the tests.
Consider using the Singleton Container pattern and check Spring Boot example

Using Spring Boot Data to read MySQL data

I'm trying to create a framework to read data from MySQL using Spring Data. The end goal is to be able to write automated tests that could read data from two different MySQL dbs and compare the data (for example, to make sure data is replicating correctly). I'm currently having loads of trouble in actually getting the Spring code to work (I've never used Spring before, I've tried modifying some various tutorial code I've found on the web, but so far haven't gotten it working.)
Here's what I've got.
MySQL
table: credentials
columns: id (int), password_hash (string)
Has 4 entries in it.
Project layout:
src/main
groovy
domain
Credentials
repository
CredentialsRepository
resources
application.properties
src/test/groovy/
CredentialsTest
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-accessing-data-jpa'
version = '0.1.0'
}
repositories {
mavenCentral()
maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.7'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.4.3.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.4.3.RELEASE'
testCompile 'junit:junit:4.11'
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/my_db
spring.datasource.username=my_user
spring.datasource.password=my_password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
Credentials.groovy
package domain
import org.springframework.data.annotation.Id
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Table
#Entity
#Table(name = 'credentials')
class Credentials {
#Id #GeneratedValue(strategy = GenerationType.AUTO) #Column(name='id')
int id
#Column(name='password_hash')
String passwordHash
protected Credentials() {}
#Override
String toString() {
"Credential: [id=${id}, passwordHash=${passwordHash}]"
}
}
CredentialsRepository.groovy
package repository
import domain.Credentials
import org.springframework.data.repository.CrudRepository
interface CredentialsRepository extends CrudRepository<Credentials, Integer> {
}
CredentialsTest.groovy
import domain.Credentials
import repository.CredentialsRepository
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import static org.junit.Assert.assertEquals
#RunWith(SpringJUnit4ClassRunner.class) //#EnableJpaRepositories(['domain.Credentials'])
#SpringBootTest(classes = MysqlJpaDemoApplication.class)
class CredentialsTest {
#Autowired
CredentialsRepository credentialsRepository
#Test
void testLoadCredentials() {
List<Credentials> credentialsList = credentialsRepository.findAll() as ArrayList<Credentials>
assertEquals(20, credentialsList.size())
}
}
Running the testLoadCredentials test gives the following stacktrace:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'CredentialsTest': Unsatisfied dependency expressed through field 'credentialsRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repository.CredentialsRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1225)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repository.CredentialsRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1474)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1102)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 33 more
2016-12-28 14:14:32.638 INFO 39748 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#742ff096: startup date [Wed Dec 28 14:14:32 PST 2016]; root of context hierarchy
Process finished with exit code 255
Seems that the application class MysqlJpaDemoApplication that you're using to configure your tests is in the default (top-level) package. As Spring runs some checks when using #ComponentScan, it will prevent your application to scan the whole classpath.
You should move MysqlJpaDemoApplication to a new package, ie,com.example. Your source folder would look like this:
src/main
/groovy/com/example
|-- /domain
| |-- Credentials.groovy
|-- /repository
| |-- CredentialsRepository.groovy
|-- MysqlJpaDemoApplicatin.groovy
Looks like this is what got it to work:
com.example/
domain/
Credentials
repository/
CredentialsRepository
SpringConfig
Credentials.groovy
#Entity
#Table(name = 'credentials')
class Credentials {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
int id
#Column(name='password_hash')
String passwordHash
protected Credentials() {}
#Override
String toString() {
"Credential: [id=${id}, passwordHash=${passwordHash}]"
}
}
CredentialsRepository
interface CredentialsRepository extends CrudRepository<Credentials, Integer> {}
SpringConfig.groovy
#Configuration
#EnableAutoConfiguration
#ComponentScan('com.example')
class SpringConfig {}
CredentialsTest.groovy
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=SpringConfig.class)
#SpringBootTest(classes = SpringConfig.class)
class CredentialsTest {
#Autowired
CredentialsRepository credentialsRepository
#Test
void testLoadCredentials() {
List<Credentials> credentialsList = credentialsRepository.findAll() as ArrayList<Credentials>
assertEquals(4, credentialsList.size())
}
}

Spring Boot DB Migration with Flyway to MySQL

I have a Gradle Spring Boot web application that migrates from H2 to PostgreSQL using Flyway. I am trying to convert this to migrate from H2 to MySQL. The build.gradle file is:
buildscript {
ext {
springBootVersion = '1.3.0.RELEASE'
}
repositories {
maven { url "http://repo.spring.io/milestone" }
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'
war {
baseName = 'demo'
version = '0.0.1-SNAPSHOT'
archiveName = 'demo.war'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
maven { url "http://repo.spring.io/milestone" }
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-security")
compile("com.h2database:h2")
compile("org.postgresql:postgresql:9.4-1201-jdbc41")
compile("org.flywaydb:flyway-core")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '1.12'
}
There is an application.yml file:
error:
whitelabel:
enabled: false
amazon:
associate_id: habuma-20
spring:
jpa:
hibernate:
ddl-auto: none
---
spring:
profiles: production
datasource:
url: jdbc:postgresql://localhost:5432/readinglist
username: habuma
password:
jpa:
database-platform: org.hibernate.dialect.PostgreSQLDialect
In build.gradle, I replaced
compile("org.postgresql:postgresql:9.4-1201-jdbc41")
with
compile("mysql:mysql-connector-java:5.1.5")
and changed application.yml to
error:
whitelabel:
enabled: false
amazon:
associate_id: habuma-20
spring:
jpa:
hibernate:
ddl-auto: none
---
spring:
profiles: production
datasource:
url: jdbc:mysql://localhost:3306/readinglist
username: root
password: ******
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
To get the "production" profile I set an environment variable SPRING_PROFILES_ACTIVE=production. Then run with the command java -jar build/libs/demo.war. When the application tries to boot up I get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception;
nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private readinglist.ReaderRepository readinglist.SecurityConfig.readerRepository;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'readerRepository': Cannot create inner bean '(inner bean)#1c65a791' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1c65a791': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed;
nested exception is org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 1
I'm not sure what the solution to this Checksum mismatch is.

ClassNotFoundException when trying to deploy a DataSource with #DataSourceDefinition

I'm trying to deploy a datasource with the #DataSourceDefinition-Annotation.
When wildfly deploys the jar, it throws a ClassNotFoundException.
I put the mysql-jdbc-Driver in the deployment-directory. I already use the com.mysql.jdbc.Driver class in Datasources configured in standalone.xml. I havn't created a module with the jdbc-driver under "modules\system\layers\base"
Here is the Class with the Annotation:
#Stateless
#DataSourceDefinition(name = "java:global/jdbc/testingDS",
className = "com.mysql.jdbc.Driver",
portNumber = 3306,
serverName = "localhost",
databaseName = "testing",
user = "testing",
password = "testing")
public class DataSourceDeployment {
public void someMethod() { }
}
And here is the Exception (this is the *.failed-File):
{
"JBAS014671: Failed services" => {"jboss.deployment.unit.\"DatasourceDeploymentTest-1.jar\".INSTALL" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"DatasourceDeploymentTest-1.jar\".INSTALL: JBAS018733: Failed to process phase INSTALL of deployment \"DatasourceDeploymentTest-1.jar\"
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from [Module \"deployment.DatasourceDeploymentTest-1.jar:main\" from Service Module Loader]
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from [Module \"deployment.DatasourceDeploymentTest-1.jar:main\" from Service Module Loader]"},
"JBAS014771: Services with missing/unavailable dependencies" => [
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.InstanceName is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.ORB is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.deployment.unit.\"DatasourceDeploymentTest-1.jar\".weld.weldClassIntrospector is missing [jboss.deployment.unit.\"DatasourceDeploymentTest-1.jar\".beanmanager]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.HandleDelegate is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.ValidatorFactory is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.InAppClientContainer is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.Validator is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]"
]
}
CFNE is just as it should be.
You have mysql jdbc driver in module but your deployment and it's #DataSourceDefinition know noting about it.
#DataSourceDefinition uses deployments classloader to load the jdbc driver but it is not available to it as it is in module.
To solve this you should either
1) add deployment's dependency to your mysql driver module via manifest.mf / jboss-deployment-structure.xml, see https://docs.jboss.org/author/display/WFLY8/Class+Loading+in+WildFly for details how
2) add jdbc driver to your war's lib directory
but I would definitely go with 1)

How to start spring-boot app without depending on Database?

I am using "Spring-boot + Hibernate4 + mysql" for my application. As part of which I have a requirement where my sprint-boot app should be able to start even when database is down. Currently it gives the below exception when I try to start my spring boot app without DB being up.
I researched a lot and found out that this exception has to do with hibernate.temp.use_jdbc_metadata_defaults property.
I tried setting this in "application.yml" of spring boot but this property's value is not being reflected at runtime.
Exception Stack Trace:
2014-05-25 04:09:43.193 INFO 59755 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
2014-05-25 04:09:43.250 WARN 59755 --- [ main] o.h.e.jdbc.internal.JdbcServicesImpl : HHH000342: Could not obtain connection to query metadata : Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
2014-05-25 04:09:43.263 INFO 59755 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
Error starting ApplicationContext. To display the auto-configuration report enabled debug logging (start with --debug)
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:648)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
at admin.Application.main(Application.java:36)
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:399)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:150)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:336)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 15 more
application.yml:
spring:
jpa:
show-sql: true
hibernate:
ddl-auto: none
naming_strategy: org.hibernate.cfg.DefaultNamingStrategy
temp:
use_jdbc_metadata_defaults: false
It was indeed a tough nut to crack.
After lot and lot of research and actually debugging the spring-boot, spring, hibernate, tomcat pool, etc to get it done.
I do think that it will save lot of time for people trying to achieve this type of requirement.
Below are the settings required to achieve the following requirement
Spring boot apps will start fine even if DB is down or there is no DB.
Apps will pick up the connections on the fly as DB comes up which means there is no need to restart the web server or redeploy the apps.
There is no need to start the tomcat or redeploy the apps, if DB goes down from running state and comes up again.
application.yml :
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/schema
username: root
password: root
continueOnError: true
initialize: false
initialSize: 0
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 5000
minIdle: 0
jpa:
show-sql: true
hibernate:
ddl-auto: none
naming_strategy: org.hibernate.cfg.DefaultNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
hbm2ddl:
auto: none
temp:
use_jdbc_metadata_defaults: false
I am answering here and will close the issue that you have cross-posted
Any "native" property of the JPA implementation (Hibernate) can be set using the spring.jpa.properties prefix as explained here
I haven't looked much further in the actual issue here but to answer this particular question, you can set that hibernate key as follows
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults
Adding this alone worked for me:
spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.Oracle10gDialect
Just replace the last part with your database dialect.
The solution is really useful for me. Thanks
i used file "application.properties" includes following lines:
app.sqlhost=192.168.10.11
app.sqlport=3306
app.sqldatabase=logs
spring.main.web-application-type=none
# Datasource
spring.datasource.url=jdbc:mysql://${app.sqlhost}:${app.sqlport}/${app.sqldatabase}
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.hbm2dll.auto = none
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.datasource.continue-on-error=true
spring.datasource.initialization-mode=never
spring.datasource.hikari.connection-timeout=5000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.initialization-fail-timeout= -1
spring.jpa.hibernate.use-new-id-generator-mappings=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.output.ansi.enabled=always
But, you can not use #Transactional annotation at class level
#Service
//#Transactional //do not use to touch the Repository
#EnableAsync
#Scope( proxyMode = ScopedProxyMode.TARGET_CLASS )
public class LogService {
.... }
#Async
#Transactional // you can use at function level
public void deleteLogs(){
logRepository.deleteAllBy ...
}
Add following config should be work:
spring.jpa.database-platform: org.hibernate.dialect.MySQL5Dialect