I'm currently learning microservices. After creating my first microservice, I tried to connect my microservice to a PostgreSQL database but I have the following error:
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
With this exception:
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; 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
2022-12-06 22:33:04.408 INFO 2012 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
Here's my application.yml
server:
port: 8080
spring:
application:
name: player
datasource:
password: "MySecretPassword!"
url: jdbc:postgresql://localhost:5432/genjiservices
username: saucegenji
jpa:
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: true
show-sql: true
I couldn't post my pom because it says it was a spam.
I tried to find solutions first, but couldn't find one that works for me. I think my application is ignoring my application.yml could that be the case? My application.yml is in the resources folder like it should be, so I don't really understand.
Check if the following is present in the pom file.Also check for JPA dependencies in pom.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Related
I want to share a problem I had when trying to upload a simple application with docker connected to postgres also in docker.
looks like it's having trouble finding the BeersRepository interface.
I've tried annotations like #ComponentScan, #EnableJpaRepository etc...
EDIT: https://github.com/teodorolucasac/beerstore
This is the error log:
`
20:48:51.989 [main] INFO com.hibicode.beerstore.BeerstoreApplication - Starting BeerstoreApplication using Java 18-ea on c97aaa0419fe with PID 1 (/app/app.jar started by root in /)
20:48:51.991 [main] DEBUG com.hibicode.beerstore.BeerstoreApplication - Running with Spring Boot, Spring
20:48:51.994 [main] INFO com.hibicode.beerstore.BeerstoreApplication - No active profile set, falling back to 1 default profile: "default"
20:48:51.996 [main] DEBUG org.springframework.boot.SpringApplication - Loading source class com.hibicode.beerstore.BeerstoreApplication
20:48:52.062 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#1a052a00
20:48:52.072 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
20:48:52.129 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Ignored because not a concrete top-level class: URL [jar:file:/app/app.jar!/com/hibicode/beerstore/repository/BeersRepository.class]
20:48:52.159 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/app/app.jar!/com/hibicode/beerstore/resource/BeerResource.class]
20:48:52.170 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/app/app.jar!/com/hibicode/beerstore/service/BeerService.class]
20:48:52.327 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
20:48:52.329 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
20:48:52.332 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
20:48:52.334 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
20:48:52.337 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor'
20:48:52.342 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beerstoreApplication'
20:48:52.349 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beerResource'
20:48:52.367 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'beerResource': Unsatisfied dependency expressed through field 'beersRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.hibicode.beerstore.repository.BeersRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
20:48:52.375 [main] ERROR org.springframework.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'beerResource': Unsatisfied dependency expressed through field 'beersRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.hibicode.beerstore.repository.BeersRepository' 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.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
at com.hibicode.beerstore.BeerstoreApplication.main(BeerstoreApplication.java:17)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.hibicode.beerstore.repository.BeersRepository' 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:1801)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1357)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656)
... 19 common frames omitted
`
Application
`
package com.hibicode.beerstore;
#SpringBootApplication
public class BeerstoreApplication {
public static void main(String[] args) {
SpringApplication.run(BeerstoreApplication.class, args);
}
}
`
Entity
`
package com.hibicode.beerstore.model;
#Entity
#Data
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Beer {
`
Repository
`
package com.hibicode.beerstore.repository;
#Repository
#EnableJpaRepositories
public interface BeersRepository extends JpaRepository<Beer, Long> {
Optional<Beer> findByNameAndType(String name, BeerType type);
}
`
Controller
`
package com.hibicode.beerstore.resource;
#RestController
#RequestMapping("/beers")
public class BeerResource {
`
Service
`
package com.hibicode.beerstore.service;
import java.util.Optional;
#Service
#Component
public class BeerService {
`
application.properties
the port is 5433 because my Docker is configured like this: 0.0.0.0:5433->5432/tcp, because I was having problem in docker with windows, and the only solution I found was to change the port of my machine
`
spring.datasource.url=jdbc:postgresql://localhost:5433/beerstore
spring.datasource.username=beerstore
spring.datasource.password=beerstore
spring.jpa.hibernate.temp.use_jdbc_metadata_defaults=false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
`
Dockerfile
PS: I was creating my project .jar through Intellij > File > Project Structure > Project Settings > Artifacts
Then Build > Build artifacts
`
FROM openjdk:18-jdk-alpine3.14
ENV LANG C.UTF-8
RUN apk add --update bash
ADD out/artifacts/beerstore_jar/*.jar /app/app.jar
CMD java -jar /app/app.jar $APP_OPTIONS
`
docker image build
docker build -t teodorolucasac/beerstore:0.3 .
docker run
docker run -p 8080:8080 --rm --network beernet -e APP_OPTIONS='--spring.datasource.url=jdbc:postgresql://beerdb:5433/beerstore' teodorolucasac/beerstore:0.3
ps: postgres is already running on docker and connected to the beernet network
Someone save me please. If any information is missing, you can ask me to post it immediately.
I tried annotations like #ComponentScan, #EnableJpaRepository etc... but it didn't work
EDIT I will post the new error message after some changes as #EnableJpaRepository.
It looks like there is some problem with entityManagerFactory.
PS: the application runs perfectly on my machine, this problem only happens when I go to docker.
new error:
`
15:07:41.192 [main] INFO com.hibicode.beerstore.BeerstoreApplication - Starting BeerstoreApplication using Java 18-ea on 755d25c6462c with PID 1 (/app/app.jar started by root in /)
15:07:41.194 [main] DEBUG com.hibicode.beerstore.BeerstoreApplication - Running with Spring Boot, Spring
15:07:41.197 [main] INFO com.hibicode.beerstore.BeerstoreApplication - No active profile set, falling back to 1 default profile: "default"
15:07:41.198 [main] DEBUG org.springframework.boot.SpringApplication - Loading source class com.hibicode.beerstore.BeerstoreApplication
15:07:41.263 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationConte
xt#1a052a00
15:07:41.271 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.inte
rnalConfigurationAnnotationProcessor'
15:07:41.343 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/app/app.jar!/com/hibicode/beersto
re/config/ApiErrorConfig.class]
15:07:41.354 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/app/app.jar!/com/hibicode/beersto
re/error/ApiExceptionHandler.class]
15:07:41.359 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/app/app.jar!/com/hibicode/beersto
re/error/GeneralExceptionHandler.class]
15:07:41.368 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Ignored because not a concrete top-level class: URL [jar:file:/app/app.jar!/com/hibico
de/beerstore/repository/BeersRepository.class]
15:07:41.388 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/app/app.jar!/com/hibicode/beersto
re/resource/BeerResource.class]
15:07:41.391 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: URL [jar:file:/app/app.jar!/com/hibicode/beersto
re/service/BeerService.class]
15:07:41.509 [main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Bootstrapping Spring Data JPA repositories in DEFAULT mode.
15:07:41.520 [main] DEBUG org.springframework.data.repository.config.RepositoryConfigurationDelegate - Scanning for JPA repositories in packages com.hibicode.beerstore.repository.
15:07:41.533 [main] DEBUG org.springframework.data.repository.config.RepositoryComponentProvider - Identified candidate component class: URL [jar:file:/app/app.jar!/com/hibicode/beerst
ore/repository/BeersRepository.class]
15:07:41.582 [main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 61 ms. Found 1 JPA repository interfac
es.
15:07:41.666 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'emBeanDefinitionRegistrarPostProcessor'
15:07:41.669 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalE
ventListenerProcessor'
15:07:41.672 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalE
ventListenerFactory'
15:07:41.675 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.inte
rnalAutowiredAnnotationProcessor'
15:07:41.677 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.inte
rnalCommonAnnotationProcessor'
15:07:41.682 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.inte
rnalPersistenceAnnotationProcessor'
15:07:41.691 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beerstoreApplication'
15:07:41.698 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'apiErrorConfig'
15:07:41.700 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'apiExceptionHandler'
15:07:41.733 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'apiErrorMessageSource'
15:07:41.753 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'apiExceptionHandler' via constructor to bean named '
apiErrorMessageSource'
15:07:41.754 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'generalExceptionHandler'
15:07:41.763 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beerResource'
15:07:41.776 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'beersRepository'
15:07:41.838 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: o
rg.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'beerResource': Unsatisfied dependency expressed through field 'beersRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beersRepository' defined in com.hibicode.beerstore.repository.BeersRepository defin
ed in #EnableJpaRepositories declared on BeerstoreApplication: Cannot create inner bean '(inner bean)#53f0a4cb' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while s
etting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#53f0a4cb': Cannot resolve
reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entity
ManagerFactory' available
15:07:41.846 [main] ERROR org.springframework.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'beerResource': Unsatisfied dependency expressed through field 'beersRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beersRepository' defined in com.hibicode.beerstore.repository.BeersRepository defi
ned in #EnableJpaRepositories declared on BeerstoreApplication: Cannot create inner bean '(inner bean)#53f0a4cb' 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)#53f0a4cb': Cannot resolv
e reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entit
yManagerFactory' available
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
at com.hibicode.beerstore.BeerstoreApplication.main(BeerstoreApplication.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beersRepository' defined in com.hibicode.beerstore.repository.BeersRepository defined
in #EnableJpaRepositories declared on BeerstoreApplication: Cannot create inner bean '(inner bean)#53f0a4cb' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while set
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330)
... 40 common frames omitted
`
you need #EnableJpaRepositories(basePackages = "YOUR_PACKAGE")
also make sure to add this in pom.xml
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
or this
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.5.0</version>
</dependency>
The goal is, to have dev and prod environments. For the local run to use application-dev.yml and for deploying to the server to use application-prod.yml
I have 3 configuration files
application.yml
spring:
main:
banner-mode: off
application-dev.yml
spring:
datasource:
password: dev-user-pwd
username: dev-user
url: jdbc:mysql://localhost:3306/db
driver-class-name: com.mysql.cj.jdbc.Driver
application-prod.yml
spring:
datasource:
password: prod-user-pwd
username: prod-user
url: jdbc:mysql://localhost:3306/db
driver-class-name: com.mysql.cj.jdbc.Driver
In the server, I have maven installed and trying to run
mvn clean package -Dspring.profiles.active=prod
Here is the error log that I'm getting
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 10.966 s <<< FAILURE! - in com.partplug.api.ApiApplicationTests
contextLoads Time elapsed: 0.005 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.web.config.SpringDataWebConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.NoClassDefFoundError: org/xmlbeam/config/XMLFactoriesConfig
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.web.config.SpringDataWebConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.NoClassDefFoundError: org/xmlbeam/config/XMLFactoriesConfig
Caused by: java.lang.NoClassDefFoundError: org/xmlbeam/config/XMLFactoriesConfig
Caused by: java.lang.ClassNotFoundException: org.xmlbeam.config.XMLFactoriesConfig
In short: the error says that, datasource and all sub-properties are not defined. Meaning, maven packager doesn't change the active profile to prod.
What am I doing wrong?
2019-07-12 17:32:57.619 WARN 24158 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is java.lang.RuntimeException: 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 java.lang.NoClassDefFoundError: org/springframework/security/web/debug/DebugFilter
2019-07-12 17:32:57.639 ERROR 24158 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is java.lang.RuntimeException: 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 java.lang.NoClassDefFoundError: org/springframework/security/web/debug/DebugFilter
What is this error? I can't find any sources to it.
Project is missing a dependency. Add below dependency in your pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
I`v got bean error...
this is error code:
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testMapper' defined in file [C:\Users\user\Desktop\workspace\SpringBootSample-4\target\classes\com\simplify\sample\db\mapper\TestMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/simplify/sample/db/DatabaseConfig.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' 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 java.lang.IllegalStateException: Cannot load driver class: com.microsoft.sqlserver.jdbc.SQLServerDriver
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testMapper' defined in file [C:\Users\user\Desktop\workspace\SpringBootSample-4\target\classes\com\simplify\sample\db\mapper\TestMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/simplify/sample/db/DatabaseConfig.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' 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 java.lang.IllegalStateException: Cannot load driver class: com.microsoft.sqlserver.jdbc.SQLServerDriver
2019-06-12 13:50:03.183 INFO 10780 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-06-12 13:50:03.242 INFO 10780 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-06-12 13:50:03.320 ERROR 10780 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
and this is config:
#Configuration
#MapperScan(basePackages="com.simplify.sample.db.mapper")
#EnableTransactionManagement
public class DatabaseConfig {
#Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sessionFactory.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));
return sessionFactory.getObject();
}
#Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
return sqlSessionTemplate;
}
}
update-1 mssql version
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.4.0.jre8</version>
<scope>test</scope>
</dependency>
What's wrong with it ?
Thanks for your interesting !
spring-boot, mybatis, mssql
Simply remove the scope from the sqlserver dependency:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.4.0.jre8</version>
</dependency>
You need this driver when running the app.
I am new in Java and I am trying to do a sample Spring Boot application. I am using eclipse IDE and Java 8. Created a Maven project with maven-archetype-quickstart archetype. In the pom.xml
<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>
<groupId>com.demo</groupId>
<artifactId>StormpathSpringBoot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>StormpathSpringBoot</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>
In App.java
package com.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
Then I run the application RunAs--> Maven Build
goal-> spring-boot:run
Don't know this is the right way to run this application
I am getting error
2017-08-03 02:33:19.294 INFO 5124 --- [ main] com.demo.App : Starting App on C4968397007 with PID 5124 (C:\Users\dev3\WS_SpringBoot\StormpathSpringBoot\target\classes started by dev3 in C:\Users\dev3\WS_SpringBoot\StormpathSpringBoot)
2017-08-03 02:33:19.297 INFO 5124 --- [ main] com.demo.App : No active profile set, falling back to default profiles: default
2017-08-03 02:33:19.518 INFO 5124 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#39dcb4f0: startup date [Thu Aug 03 02:33:19 EDT 2017]; root of context hierarchy
2017-08-03 02:33:21.121 INFO 5124 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]]
2017-08-03 02:33:21.950 INFO 5124 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fcd1a082] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-08-03 02:33:22.354 INFO 5124 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-03 02:33:22.369 INFO 5124 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-08-03 02:33:22.370 INFO 5124 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.14
2017-08-03 02:33:22.471 INFO 5124 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-08-03 02:33:22.472 INFO 5124 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2954 ms
2017-08-03 02:33:22.790 INFO 5124 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-03 02:33:22.794 INFO 5124 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-03 02:33:22.794 INFO 5124 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-03 02:33:22.794 INFO 5124 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-03 02:33:22.795 INFO 5124 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-03 02:33:23.157 WARN 5124 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'profileController' defined in URL [jar:file:/C:/Users/dev3/.m2/repository/org/springframework/data/spring-data-rest-webmvc/2.6.3.RELEASE/spring-data-rest-webmvc-2.6.3.RELEASE.jar!/org/springframework/data/rest/webmvc/ProfileController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceMappings' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.rest.core.mapping.RepositoryResourceMappings]: Factory method 'resourceMappings' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistentEntities' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mapping.context.PersistentEntities]: Factory method 'persistentEntities' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceMappings' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.rest.core.mapping.RepositoryResourceMappings]: Factory method 'resourceMappings' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistentEntities' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mapping.context.PersistentEntities]: Factory method 'persistentEntities' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.rest.core.mapping.RepositoryResourceMappings]: Factory method 'resourceMappings' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistentEntities' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mapping.context.PersistentEntities]: Factory method 'persistentEntities' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistentEntities' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mapping.context.PersistentEntities]: Factory method 'persistentEntities' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mapping.context.PersistentEntities]: Factory method 'persistentEntities' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
To run you can: in eclipse right click on project -> run as -> Java application
I use Eclipse based IDE STS - it is usually better for Spring as here initial configs are up to date and better tested
Error states, that there is no JPA mappings defined. You have to define them or delete depedndencies from POM
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
You are including spring-boot-starter-data-rest as a dependency. So there is a default controller with it (ProfileController), which is scanned at Spring context startup.
This controller has dependencies to other beans, one of which (jpaMappingContext) require a JPA configuration I guess.
Just remove this dependency and it should be fine.
As already mention in comment/answer- You have added the dependency for Spring JPA but did not add any entities in the project. You can remove this and try.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Probably the best place to start a spring-boot project is to use spring initializr.
https://start.spring.io/