I have a spring boot application with the following configuration:
Application
#SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class,
DataSourceAutoConfiguration.class,JpaRepositoriesAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {
Main configuration class:
#Configuration
#ComponentScan("com.mycompany.it")
#Import(DatabaseConfiguration.class)
public class Configuration extends WebMvcConfigurationSupport {
Database configuration:
#Configuration
#ComponentScan(basePackages = {"com.mycompany.it.xp2.integration.workday.dao","com.mycompany.it.xp2.integration.workday.application","com.company.it.xp2.integration.workday.model"})
#EnableAspectJAutoProxy
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"com.company.it.xp2.integration.workday.dao","com.company.it.xp2.integration.workday.model"})
public class DatabaseConfiguration {
With DataSource bean declaration:
#Bean(destroyMethod = "close")
#Primary
public DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource source = new ComboPooledDataSource();
source.setDriverClass(driverClass);
source.setJdbcUrl(jdbcUrl);
source.setUser(jdbcUsername);
source.setPassword(jdbcPassword);
source.setInitialPoolSize(initialSize);
source.setMaxPoolSize(maxActive);
source.setMinPoolSize(minIdle);
return source;
}
However when I start up the application I get the following error:
Caused by:
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: {}
Here are the related lines from gradle:
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop'
compile group: 'org.springframework', name: 'spring-orm'
compile group: "org.springframework.boot", name: "spring-boot-starter-jdbc"
compile "org.springframework.boot:spring-boot-starter-data-jpa"
Spring boot version 1.5.3
Check the error log
1 bean which qualifies as autowire candidate. Dependency annotations
It seems that there is an error when you configured the bean.
Related
I just created a project in spring boot, the project is clean (zero changes) just created and at first I wanted to build it with the command: ./gradlew clean build , but the build does not go through I get: BUILD FAILED (Task :test FAILED) What went wrong: Execution failed for task ':test'. java.lang.IllegalStateException: Failed to load ApplicationContext I have no idea why I'm getting an error in an application where I haven't modified anything yet. What could be the cause of this? How can I build this application?
SpringbootServerApplicationTests > contextLoads() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800
Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658
Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException at DataSourceProperties.java:182
gradle.build
plugins {
id 'org.springframework.boot' version '2.7.2'
id 'io.spring.dependency-management' version '1.0.12.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
ERROR:
Caused by: 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
at app//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658)
at app//org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638)
I think you have default test and you dont have main method that starts application. Maybe you can write some code to provide spring application to boot. Main method is enough for you. contextLoads() method test the application context be up or not. You need configure datasource as well. In your stacktrace I can see that driver is missing.
While running from IDE everything looks fine
Getting a below-mentioned error while trying to deploy the application in the tomcat server.
Caused by: 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
Application.java
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
build.gradle
plugins {
id 'java'
}
sourceCompatibility = 1.8
apply plugin: 'java'
apply plugin: 'war'
repositories {
mavenCentral()
maven { url "http://dayrhebfmi001.enterprisenet.org:8081/artifactory/libs-snapshot"}
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.7.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.1.7.RELEASE'
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.6'
compile group: 'org.projectlombok', name: 'lombok', version: '1.18.8'
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.8'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.28'
testCompile group: 'junit', name: 'junit', version: '4.12'
providedRuntime group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '2.1.8.RELEASE'
}
application.properties
spring.datasource.platform=xxxxx
spring.datasource.url=xxxxx
spring.datasource.username=xxxxx
spring.datasource.password=xxxxx
spring.jpa.show-sql=true
spring.datasource.driver-class-name=org.postgresql.Driver
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
There are a couple things that look suspicious about your properties. But I think you can solve this specific error by giving it the class name as requested.
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
(or whatever DB you're using)
Extra points for adding
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
(again, or whatever DB you're using)
EDIT:
Of course unless you've put the database driver jar file in tomcat/lib, you'll need to add that to your dependencies such that it can get bundled into the war file.
You should add driver class configuration to application.properties:
spring.datasource.driver-class-name=org.postgresql.Driver
In particular I have a subproject which belongs to a Multi-Project-Build.
The subproject has no SpringBootApplication of its own.
After some research I found out that in ClassPath #SpringBootConfiguration is searched for
But now I can't get any further because the DataSource that is configured in the application.yml is not found.
The following Exception is thrown:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'de.acme.storage.DBConnectionTest': Unsatisfied dependency expressed through field 'dataSource'; 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: {#javax.inject.Inject()}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
...
My expectation was to see the output: DataSource: HikariDataSource (HikariPool-1) as explained in a guide about Spring Boot 2 and Hikari.
However, this guide has been satisfied with a "test" in the SpringBootApplication class.
Where's my fault?
The structure of the subproject is as follows:
src
+---main
| \---java
| | \---de
| | \---acme
| | \---storage
| | +---model
| | | User.java
| | |
| | \---mysql
| | UserDAOImpl.java
|
\---test
+---java
| \---de
| \---acme
| \---storage
| DBConnectionTest.java
| TestConfig.java
|
\---resources
application.yml
The build.gradle of the subproject:
plugins {
id 'org.springframework.boot'
}
apply plugin: 'io.spring.dependency-management'
dependencies {
implementation project(':api'),
'javax.inject:javax.inject:1',
'org.springframework.boot:spring-boot-starter-data-jpa'
runtime 'mysql:mysql-connector-java'
}
The build.gradle in the main project contains this dependencies section:
dependencies {
implementation 'org.slf4j:slf4j-api'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'junit', module: 'junit' //by both name and group
}
testImplementation 'org.junit.jupiter:junit-jupiter-api',
'org.junit.jupiter:junit-jupiter-params'
testRuntime 'org.junit.jupiter:junit-jupiter-engine'
}
The application.yml content:
spring:
datasource:
url: jdbc:mysql://localhost:13306/testdb
username: test-user
password: geheim
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.MySQLDialect
format_sql: true
id:
new_generator_mappings: false
The JUnit test:
#SpringBootTest
class DBConnectionTest {
private static final Logger LOG = LoggerFactory.getLogger(DBConnectionTest.class);
#Inject
private DataSource dataSource;
#Test
void test() {
LOG.debug("DataSource: {}", dataSource);
assertThat(dataSource).as("Es gibt eine Datasource").isNotNull();
}
}
And finally the empty configuration with #SpringBootConfiguration annotation:
package de.acme.storage;
import org.springframework.boot.SpringBootConfiguration;
#SpringBootConfiguration
class TestConfig {
}
There was just one little thing missing, the annotation #EnableAutoConfiguration. Thought this would be done by #SpringBootConfiguration...
package de.acme.storage;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
#SpringBootConfiguration
#EnableAutoConfiguration
class TestConfig {
}
I'm trying to test my application following samples on the Spring website.
These are my dependencies:
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile("org.springframework.boot:spring-boot-starter-security")
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity4")
runtime('org.springframework.boot:spring-boot-devtools')
runtime('com.h2database:h2')
runtime('mysql:mysql-connector-java')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.springframework.security:spring-security-test')
}
And this is the test class:
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class ProductControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void testHomePage() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk());
}
}
I get the error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
java.lang.IllegalStateException: Failed to load ApplicationContext
Any idea what may be causing this? I don't have any specific configuration files, only the a security configuration and a webconfig.
Webconfig:
public class WebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**", "/css/**", "/fragments/**")
.addResourceLocations("classpath:/static/images/", "classpath:/static/css/", "classpath:/fragments/");
}
}
The following line in the output:
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
Tells us that the class javax.xml.bind.JAXBException is not found.
As #Antot mentionned, adding the following dependency to your graddle should fix the issue:
compile('javax.xml.bind:jaxb-api:2.3.0')
For those using Maven, use the following:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
I'd like to make use of spring-data-jpa and CrudRepository<T, ID extends Serializable>. But I cannot get it autowired. (all other services in the same package are wired correctly):
#Service
public class UserService {
#Resource
private UserRepo repo;
//this does neither work
//#Autowired
//private CrudRepository<User, Long> repo;
}
public interface UserRepo extends CrudRepository<User, Long> {
}
#Entity
public class User {
#Id
private Long id;
}
Result:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userService': Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [UserRepo] found for dependency: expected at
least 1 bean which qualifies as autowire candidate for this
dependency. Dependency annotations:
{#javax.annotation.Resource(shareable=true, mappedName=, description=,
name=, type=class java.lang.Object, lookup=,
authenticationType=CONTAINER)}
What might be wrong here?
From the docs I think it should work without writing an implementation:
In a typical Java application, you’d expect to write a class that
implements CustomerRepository. But that’s what makes Spring Data JPA
so powerful: You don’t have to write an implementation of the
repository interface. Spring Data JPA creates an implementation on the
fly when you run the application.
Updated SpringConfig:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("my.package")
public class AppConfig {
#Bean
public LocalContainerEntityManagerFactoryBean emf() throws ClassNotFoundException, PropertyVetoException {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setPackagesToScan("my.package");
emf.setJpaVendorAdapter(jpaAdapter());
emf.setJpaProperties(jpaProterties());
return emf;
}
}
Result: emf is missing, which is strange as I already have working DAO serices where I can autowire EntityManager and EMF without any problem.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1a6e658': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:632)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:442)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
... 50 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:641)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
... 58 more
You should verify the following:
1) Annotate the UserRepo with #Repository.
2) Your spring beans xml file should have in it:
<jpa:repositories base-package="your.repository.package"></jpa:repositories>
3) I'd recommend injecting this type of bean with #Autowired instead of #Resource
UPDATE
it seems you did my first 3 steps and you're one step ahead now. Now, remember that in Java Config methods names DO matter. Either change emf() to entityManagerFactory() (which is more "standard"), or set entity-manager-factory-ref to emf. Example:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException, PropertyVetoException {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setPackagesToScan("my.package");
emf.setJpaVendorAdapter(jpaAdapter());
emf.setJpaProperties(jpaProterties());
return emf;
}
Doesn't UserRepo needs to be annotated with :
#Repository
It must be an issue in your applicationContext configuration. Here is the one I used to made it work:
<jpa:repositories
base-package="package.containing.your.repositories"
factory-class="org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory" />
<bean
id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean
id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<bean
id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:persistenceUnitName="PU"
p:jpaVendorAdapter-ref="hibernateJpaVendorAdapter"
p:jpaProperties="classpath:hibernate.properties" />
<util:property-path id="sessionFactory" path="entityManagerFactory.sessionFactory" />
Configuring spring data JPA using XML and annotations
//This is the two way to configure spring data JPA
#EnableJpaRepositories (basePackages= "Repository Bean is located in package", entityManagerFactoryRef= "Here is your configuration of EntityManagerFactoryBean")
<jpa:repositories base-package= "Repository Bean where package"
Entity-manager-factory-ref= "Here is your configured EntityManagerFactoryBean" ></jpa:repositories>
// Sample code:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages="com.zxg.springdata",
entityManagerFactoryRef="factoryBean")
public class SpringDataConfig {
#Bean
public LocalContainerEntityManagerFactoryBean factoryBean (
ComboPooledDataSource dataSource, JpaVendorAdapter jpaVendorAdapter
){
LocalContainerEntityManagerFactoryBean factoryBean = new
LocalContainerEntityManagerFactoryBean ();
FactoryBean.setDataSource (dataSource);
FactoryBean.setJpaVendorAdapter (jpaVendorAdapter);
FactoryBean.setPackagesToScan ("com.zxg.springdata");
Return factoryBean;
}
}