#Autowired BeanCreationException with JUnit - java

I know this question has been asked many times but I've been stuck on this for a few days and cannot figure out why this is happening.
Here is my JUnit test suite, and the issue happens when I try to #Autowire RequestService:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:**/*.xml"})
public class RequestServiceTest {
#Autowired
private RequestService requestService;
#Test
public void add() throws Exception {
requestService.add(new Request(1, "hello"));
requestService.add(new Request(2, "hi"));
Request requestResponseFromDatabase = (Request) requestService.findById(1);
assertEquals("hello", requestResponseFromDatabase.getRestRequestParameters());
}
}
Below is my code for my model, DAO, and service classes.
Model (leaving out the constructor and other fields for brevity)
#Entity
public class Request implements Serializable {
#Id
private Integer restRequestId;
private Timestamp restRequestTimestamp;
private String restRequestParameters;
}
DAO
#Component
public class RequestDAO {
#Autowired
private RequestService requestService;
#PersistenceContext
private EntityManager entityManager;
public void persist(Request request) {
entityManager.persist(request);
}
public void update(Request request) {
entityManager.getTransaction().begin();
entityManager.merge(request);
entityManager.getTransaction().commit();
}
public Object findById(Serializable id) {
Request request = entityManager.find(Request.class, id);
if (request == null) {
throw new EntityNotFoundException("Cannot find Request for ID " + id);
}
return request;
}
public void delete(Request request) {
entityManager.getTransaction().begin();
entityManager.remove(request);
entityManager.getTransaction().commit();
}
public void deleteById(Serializable id) {
Request request = entityManager.find(Request.class, id);
if (request == null) {
throw new EntityNotFoundException("Cannot find Request for ID " + id);
} else if (request != null) {
entityManager.getTransaction().begin();
entityManager.remove(request);
entityManager.getTransaction().commit();
}
}
public List<Request> findAll() {
Query query = entityManager.createQuery("SELECT e from Request e");
List<Request> requests = query.getResultList();
return requests;
}
public void deleteAll() {
List<Request> requests = findAll();
for (Request request : requests) {
delete(request);
}
}
}
Service
#Component
public class RequestService {
#Autowired
private RequestDAO requestDAO;
#Transactional
public void add(Request request) {
requestDAO.persist(request);
}
#Transactional
public void update(Request request) {
requestDAO.update(request);
}
#Transactional
public Object findById(Serializable id) {
return requestDAO.findById(id);
}
#Transactional
public void delete(Request request) {
requestDAO.delete(request);
}
#Transactional
public void deleteById(Request request) {
requestDAO.delete(request);
}
#Transactional
public void deleteAll() {
requestDAO.deleteAll();
}
#Transactional
public void addAll(Collection<Request> requestCollection) {
for (Request request : requestCollection) {
requestDAO.persist(request);
}
}
#Transactional(readOnly = true)
public List<Request> findAll() {
return requestDAO.findAll();
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans -->
<context:component-scan base-package="com.company.mypackage"/>
<!-- Activates scanning of #Autowired -->
<context:annotation-config/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem://requestDb"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="com.company.mypackage"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
<bean id="transactionManger" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManger"/>
</beans>
Full stacktrace:
May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#3498ed, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#1a407d53, org.springframework.test.context.support.DirtiesContextTestExecutionListener#3d8c7aca, org.springframework.test.context.transaction.TransactionalTestExecutionListener#5ebec15, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#21bcffb5]
May 23, 2016 1:57:38 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext#548b7f67: startup date [Mon May 23 13:57:38 EDT 2016]; root of context hierarchy
May 23, 2016 1:57:38 PM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#1a407d53] to prepare test instance [com.company.mypackage.request.service.RequestServiceTest#57175e74]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.company.mypackage.request.service.RequestServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
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.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
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:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 30 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 32 more
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.company.mypackage.request.service.RequestServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
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.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
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:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 30 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 32 more
Process finished with exit code -1
Additional Details
Spring version: 4.2.5.RELEASE
Hibernate version: 5.1.0.Final
My spring.xml is located within src/main/resources (yes I am aware that it is not the best practice but wanted to make sure my tests work first. I did try to keep it in my src/test/resources folder but kept getting issues with my ApplicationContext not being able to load)
Resources followed:
#Autowired with JUnit tests
#AUTOWIRED : BeanCreationException
#Autowired fails with JUnit & Spring
Spring not autowiring in unit tests with JUnit
Spring ORM example with JPA, Hibernate, Transactions
Any ideas on how to resolve this? I have asked similar questions to this in the past and do apologize - having a hard time understanding Spring along with all of it's documentation. I want to make sure I fully understand this to avoid making the same mistake in the future.
EDIT: Here is my folder structure:
Stack trace when using #ContextConfiguration(locations = {"classpath:spring.xml"}):
May 23, 2016 3:20:39 PM org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
May 23, 2016 3:20:39 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#60f82f98, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#35f983a6, org.springframework.test.context.support.DirtiesContextTestExecutionListener#7f690630, org.springframework.test.context.transaction.TransactionalTestExecutionListener#edf4efb, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#2f7a2457]
May 23, 2016 3:20:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
May 23, 2016 3:20:39 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext#174d20a: startup date [Mon May 23 15:20:39 EDT 2016]; root of context hierarchy
May 23, 2016 3:20:39 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.hsqldb.jdbcDriver
May 23, 2016 3:20:39 PM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'default'
May 23, 2016 3:20:39 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: default
...]
May 23, 2016 3:20:39 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
May 23, 2016 3:20:39 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 23, 2016 3:20:39 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 23, 2016 3:20:39 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 23, 2016 3:20:40 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : User not found: USER
May 23, 2016 3:20:40 PM org.springframework.context.support.GenericApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
May 23, 2016 3:20:40 PM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#35f983a6] to prepare test instance [com.company.mypackage.request.service.RequestServiceTest#481ba2cf]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
java.lang.IllegalStateException: Failed to load ApplicationContext
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Process finished with exit code -1

The error msg is very clear, you need to config your hibernate properly.
org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
The possible reason could be:
You haven't setup your hibernate properly.
or there is no DB running during the test

The problem happening over here is it is not able to load your spring bean xml file. can you put your spring xml file directly at the root level in the classpath.

Related

No qualifying bean of type 'org.springframework.data.jpa.repository.support.JpaEntityInformation

I'm trying to extend the **SimpleJpaRepository ** by BaseRepository interface and the BaseRepositoryImpl.
Tha BaseRepositoryImpl extends **SimpleJpaRepository ** and implements BaseRepository.
In addition, I have some other Repositories such as CandidateRepository and EmployeeRepository that extends the BaseRepository.
Below you can see the code following the error:
To see the project structure click here
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>{
//..
}
#Repository
public abstract class BaseRepositoryImpl<T, ID extends Serializable> extends
SimpleJpaRepository<T, ID> implements BaseRepository<T, ID>{
private final EntityManager em;
public BaseRepositoryImpl(JpaEntityInformation<T,ID> entityInformation,
EntityManager entityManager) {
super(entityInformation, entityManager);
this.em = entityManager;
}
//..
}
The extend Repositories:
#NoRepositoryBean
public interface CandidateRepository extends BaseRepository<DatCandidate, UUID>{
//..
}
#Repository(value="CandidateRepositoryImpl")
public class CandidateRepositoryImpl extends BaseRepositoryImpl<DatCandidate, UUID> implements CandidateRepository{
public CandidateRepositoryImpl(
JpaEntityInformation<DatCandidate, UUID> entityInformation,
EntityManager entityManager) {
super(entityInformation, entityManager);
}
}
Here is my configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.projects"></context:component-scan>
<jpa:repositories base-package="com.projects.repositories.impl"
base-class="com.projects.repositories.impl.BaseRepositoryImpl"></jpa:repositories>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<entry key="hibernate.hbm2ddl.auto" value="none"/>
<entry key="hibernate.format_sql" value="true" />
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/relocationdb?autoReconnect=true" />
<property name="username" value="root"></property>
<property name="password" value="1234" />
</bean>
</beans>
Service:
#Service(value="CandidateServiceImpl")
public class CandidateServiceImpl extends BaseServiceImpl<CandidateForCreationDto, CandidateDto,DatCandidate, UUID>
implements CandidateService{
private CandidateRepositoryImpl candidateRepository;
#Autowired
public CandidateServiceImpl (
#Qualifier("CandidateRepositoryImpl") JpaRepository<DatCandidate, UUID> candidateRepository
) {
this.candidateRepository = (CandidateRepositoryImpl)candidateRepository;
}
}
The Error:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies
as autowire candidate. Dependency annotations: {}
I followed the Spring JPA documentation, but can't understand the error
attached is the running code
4:39:10 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate
Core {5.2.12.Final} March 21, 2018 4:39:10 PM
org.hibernate.cfg.Environment INFO: HHH000206:
hibernate.properties not found March 21, 2018 4:39:10 PM
org.hibernate.annotations.common.reflection.java.JavaReflectionManager
INFO: HCANN000001: Hibernate Commons Annotations
{5.0.1.Final} March 21, 2018 4:39:12 PM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect:
org.hibernate.dialect.MySQL5InnoDBDialect March 21, 2018 4:39:16 PM
org.apache.catalina.core.StandardContext listenerStart SEVERE:
Exception sending context initialized event to listener instance of
class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'candidateController': Unsatisfied
dependency expressed through field 'candidateBaseService'; nested
exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'CandidateServiceImpl' defined in file
[C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\service\impl\CandidateServiceImpl.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'CandidateRepositoryImpl' defined in
file
[C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\repositories\impl\CandidateRepositoryImpl.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies
as autowire candidate. Dependency annotations: {} at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5110)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5633)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748) Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'CandidateServiceImpl' defined in file
[C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\service\impl\CandidateServiceImpl.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'CandidateRepositoryImpl' defined in
file
[C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\repositories\impl\CandidateRepositoryImpl.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies
as autowire candidate. Dependency annotations: {} at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at
org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 24 more Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'CandidateRepositoryImpl' defined in
file
[C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\repositories\impl\CandidateRepositoryImpl.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies
as autowire candidate. Dependency annotations: {} at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at
org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815)
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:721)
... 37 more Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies
as autowire candidate. Dependency annotations: {} at
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815)
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:721)
... 51 more
מרץ 21, 2018 4:39:16 PM org.apache.catalina.core.StandardContext
startInternal SEVERE: One or more listeners failed to start. Full
details will be found in the appropriate container log file מרץ 21,
2018 4:39:16 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/Relocation] startup failed due to previous errors
מרץ 21, 2018 4:39:16 PM org.apache.catalina.core.ApplicationContext
log INFO: Closing Spring root WebApplicationContext מרץ 21, 2018
4:39:16 PM org.apache.catalina.loader.WebappClassLoaderBase
clearReferencesJdbc SEVERE: The web application [/Relocation]
registered the JDBC driver [com.mysql.jdbc.Driver] but failed to
unregister it when the web application was stopped. To prevent a
memory leak, the JDBC Driver has been forcibly unregistered. מרץ 21,
2018 4:39:16 PM org.apache.catalina.loader.WebappClassLoaderBase
clearReferencesThreads SEVERE: The web application [/Relocation]
appears to have started a thread named [Abandoned connection cleanup
thread] but has failed to stop it. This is very likely to create a
memory leak. מרץ 21, 2018 4:39:16 PM
org.apache.coyote.AbstractProtocol start INFO: Starting
ProtocolHandler ["http-bio-8080"] מרץ 21, 2018 4:39:16 PM
org.apache.coyote.AbstractProtocol start INFO: Starting
ProtocolHandler ["ajp-bio-8009"] מרץ 21, 2018 4:39:16 PM
org.apache.catalina.startup.Catalina start INFO: Server startup in
17422 ms
You are doing a somewhat weird combination of things here.
On the one hand, you effectively disable all the Spring Data stuff by using #NoRepositoryBean on CandidateRepository and providing your own implementation. But then your implementation is based extends SimpleJpaRepository<T, ID> which is a core component of Spring Data but it doesn't get configured properly since you basically disabled it.
I guess it's time to make up your mind:
Do you want to change the behavior that is provided by SimpleJpaRepository<T, ID>? Possibly adding methods to your base implementation.
If so extend it, leaving constructors as they are and use it as your repositoryBaseClass. Here is a tutorial how to do that.
Just provide custom implementation for one (or some) repositories. Then use custom implementations.
Being pragmatic, you're trying to extend SimpleJpaRepository<T, ID>, but once you disabling it Spring does not load any implementation of JpaEntityInformation and thus the exception.
Also, as #jens-schauder said, your mixing concepts.
Try to follow this very well explained tutorial to see if it helps.

AspectJ Cannot resolve reference to bean 'selectAll'

Here are classes and xml configuration for Java/AspectJ demo project, but it fails. Project is built in eclipse. I searched on the net, added all libraries but it still fails. Any idea what might be wrong?
UPDATE: These classes were added to eclipse aspectj project:
aopalliance.jar
asm.jar
aspectj.jar
aspectjrt.jar
aspectjtools.jar
aspectjweaver.jar
cglib.jar
org.aspectj.matcher.jar
class MainApp:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) context.getBean("student");
student.getName();
student.getAge();
student.printThrowException();
}
}
class Logging:
package com.tutorialspoint;
public class Logging {
/**
* This is the method which I would like to execute before a selected method
* execution.
*/
public void beforeAdvice() {
System.out.println("Going to setup student profile.");
}
/**
* This is the method which I would like to execute after a selected method
* execution.
*/
public void afterAdvice() {
System.out.println("Student profile has been setup.");
}
/**
* This is the method which I would like to execute when any method returns.
*/
public void afterReturningAdvice(Object retVal) {
System.out.println("Returning:" + retVal.toString());
}
/**
* This is the method which I would like to execute if there is an exception
* raised.
*/
public void AfterThrowingAdvice(IllegalArgumentException ex) {
System.out.println("There has been an exception: " + ex.toString());
}
}
class Student:
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age);
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name);
return name;
}
public void printThrowException() {
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
Beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:config>
<aop:aspect id="log" ref="logging">
<aop:pointcut id="selectAll"
expression="execution(* com.tutorialspoint.*.*(..))"/>
<aop:before pointcut-ref="selectAll" method="beforeAdvice"/>
<aop:after pointcut-ref="selectAll" method="afterAdvice"/>
<aop:after-returning pointcut-ref="selectAll"
returning="retVal"
method="afterReturningAdvice"/>
<aop:after-throwing pointcut-ref="selectAll"
throwing="ex"
method="AfterThrowingAdvice"/>
</aop:aspect>
</aop:config>
<!-- Definition for student bean -->
<bean id="student" class="com.tutorialspoint.Student">
<property name="name" value="Zara" />
<property name="age" value="11"/>
</bean>
<!-- Definition for logging aspect -->
<bean id="logging" class="com.tutorialspoint.Logging"/>
</beans>
Stack trace:
Jan 19, 2017 9:43:02 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#27bc2616: startup date [Thu Jan 19 21:43:02 CET 2017]; root of context hierarchy
Jan 19, 2017 9:43:02 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
Jan 19, 2017 9:43:02 PM org.springframework.context.support.ClassPathXmlApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#aec6354' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#aec6354': Cannot resolve reference to bean 'selectAll' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'selectAll': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/tools/PointcutPrimitive
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#aec6354' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#aec6354': Cannot resolve reference to bean 'selectAll' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'selectAll': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/tools/PointcutPrimitive
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:313)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:648)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1056)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.tutorialspoint.MainApp.main(MainApp.java:8)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#aec6354': Cannot resolve reference to bean 'selectAll' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'selectAll': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/tools/PointcutPrimitive
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1056)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:299)
... 17 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'selectAll': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/tools/PointcutPrimitive
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1060)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 25 more
Caused by: java.lang.NoClassDefFoundError: org/aspectj/weaver/tools/PointcutPrimitive
at org.springframework.aop.aspectj.AspectJExpressionPointcut.<clinit>(AspectJExpressionPointcut.java:87)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1108)
... 31 more
It's a long stack trace, but the most relevant part is the NoClassDefFoundError near the end:
Caused by: java.lang.NoClassDefFoundError: org/aspectj/weaver/tools/PointcutPrimitive at org.springframework.aop.aspectj.AspectJExpressionPointcut.(AspectJExpressionPointcut.java:87) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1108) ... 31 more
This indicates the AspectJ classes were not available to the JVM on the runtime classpath. However this application is invoked, you'll need to ensure that the aspectjweaver.jar file is on the runtime classpath. For a project managed by Maven, you could specify it as a dependency in pom.xml. Using purely Eclipse, another option would be to download aspectjweaver.jar (and all of its dependencies) and add it directly to the Eclipse project as an external library.

spring 3, hibernate, dbcp and derby connection issue

I am using Spring 3, hibernate 3, derby 10.11 and apache DBCP2. I am using a dao(TestDao) to create the hibernate session factory. This DAO is auto-wired.
I am getting the following exception when IOC is trying to instantiate the dao.
package com.springtest.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import com.springtest.entities.HotelAvailability;
#Repository
public class TestDao {
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public List<HotelAvailability> getHotels() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(HotelAvailability.class);
List<HotelAvailability> hotels = (List<HotelAvailability>) criteria.list();
session.getTransaction().commit();
return hotels;
}
applicationcontext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.springtest"/>
<bean id="datasource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="url" value="jdbc:derby://localhost:1527/home/atanu/derby/testdb"/>
<property name="initialSize" value="2"/>
<property name="maxTotal" value="5"/>
<!-- <property name="username" value="atanu"/>
<property name="password" value="passw0rd"/> -->
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="packagesToScan" value="com.springtest.entities"/>
<property name="hibernateProperties">
<props>
<prop key="dialect">
org.hibernate.dialect.DerbyDialect
</prop>
</props>
</property>
</bean>
<aop:aspectj-autoproxy/>
<aop:config>
<aop:pointcut expression="execution(* com.springtest.di.Party.getType(..))"
id="mypointcut"/>
<aop:aspect ref="myadvice">
<!-- <aop:before method="before" pointcut-ref="mypointcut"/>
<aop:after method="after" pointcut-ref="mypointcut"/> -->
<aop:around method="watchPartyCreation" pointcut-ref="mypointcut" />
</aop:aspect>
<aop:aspect>
<aop:declare-parents types-matching="com.springtest.di.Party+aopParent"
implement-interface="com.springtest.di.AopParent"
default-impl="com.springtest.di.AopParentImpl"/>
</aop:aspect>
</aop:config>
</beans>
Exception:
Sep 19, 2015 1:53:00 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#1904b13: startup date [Sat Sep 19 13:53:00 IST 2015]; root of context hierarchy
Sep 19, 2015 1:53:00 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Sep 19, 2015 1:53:00 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#4336ff: defining beans [person,testDI,compositeBean,myadvice,organization,testDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,datasource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,mypointcut,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.DeclareParentsAdvisor#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.annotations.Version <clinit>
INFO: Hibernate Annotations 3.3.0.GA
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2 cr4
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: com.springtest.entities.HotelAvailability
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.annotations.EntityBinder bindTable
INFO: Bind entity com.springtest.entities.HotelAvailability on table HOTELAVAILABILITY
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.AnnotationConfiguration secondPassCompile
INFO: Hibernate Validator not found: ignoring
Sep 19, 2015 1:53:01 PM org.springframework.orm.hibernate3.LocalSessionFactoryBean buildSessionFactory
INFO: Building new Hibernate SessionFactory
Sep 19, 2015 1:53:01 PM org.hibernate.cfg.AnnotationConfiguration secondPassCompile
INFO: Hibernate Validator not found: ignoring
Sep 19, 2015 1:53:01 PM org.hibernate.connection.ConnectionProviderFactory newConnectionProvider
INFO: Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
Sep 19, 2015 1:53:01 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#4336ff: defining beans [person,testDI,compositeBean,myadvice,organization,testDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,datasource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,mypointcut,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.DeclareParentsAdvisor#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testDI': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.springtest.dao.TestDao com.springtest.di.TestDI.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.springtest.dao.TestDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.apache.derby.client.net.NetConnection.isValid(I)Z
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.springtest.di.TestDI.loadSpringContext(TestDI.java:21)
at com.springtest.di.TestDI.main(TestDI.java:32)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.springtest.dao.TestDao com.springtest.di.TestDI.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.springtest.dao.TestDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.apache.derby.client.net.NetConnection.isValid(I)Z
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
... 14 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.springtest.dao.TestDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.apache.derby.client.net.NetConnection.isValid(I)Z
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:912)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
... 16 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.springtest.dao.TestDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.apache.derby.client.net.NetConnection.isValid(I)Z
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
... 27 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.apache.derby.client.net.NetConnection.isValid(I)Z
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:912)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
... 29 more
Caused by: java.lang.AbstractMethodError: org.apache.derby.client.net.NetConnection.isValid(I)Z
at org.apache.commons.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:918)
at org.apache.commons.dbcp2.PoolableConnection.validate(PoolableConnection.java:283)
at org.apache.commons.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:357)
at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2307)
at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2290)
at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2039)
at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:83)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:76)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1933)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1216)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:915)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:863)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:782)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
... 39 more
DBCP seems to be configured to test the validity of the connections by calling Connection.isValid(), but the implementation of Connection provided by the JDBC driver you're using is based on an older version of the JDBC API which didn't have this method yet.
I guess that Derby must have a newer driver that supports this method (you're using old versions of Spring and Hibernate, so I guess you also have an old version of the driver).
If it doesn't, then I guess you should also be able to configure DBCP not to test the validity of connections, or to test it in another way.
If you're starting a new project, then please don't use Spring 3 and Hibernate 3. They're both very old. Upgrade to their latest version, and enjoy all the improvements and bug fixes that have been made in the last 5 years.

Spring web application, Injection of autowired dependencies fail

I am setting up a simple Hello World web application with Spring and Maven.
Somehow, I keep getting a BeanCreationException when trying to autowire my test bean.
Hello Bean:
package de.dijon.test;
public class HelloBean {
private String name;
public void setName(String name) {
this.name = name;
}
public String getHello() {
return ("Hello " + name);
}
}
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
application-context.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="helloBean" class="de.dijon.test.HelloBean"
autowire="byType">
<property name="name" value="Dijon" />
</bean>
</beans>
My test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath*:/application-context.xml" })
public class AppTest extends TestCase {
#Autowired
private HelloBean obj;
#Test
public void test() {
assertNotNull(obj.getHello());
}
}
Errormessage:
Dec 23, 2013 1:31:59 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext#2b275d39: startup date [Mon Dec 23 13:31:59 CET 2013]; root of context hierarchy
Dec 23, 2013 1:31:59 PM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#371bed71] to prepare test instance [null(de.dijon.test.test.AppTest)]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'de.dijon.test.test.AppTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private de.dijon.test.HelloBean de.dijon.test.test.AppTest.obj; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [de.dijon.test.HelloBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:384)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:326)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private de.dijon.test.HelloBean de.dijon.test.test.AppTest.obj; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [de.dijon.test.HelloBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [de.dijon.test.HelloBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 28 more
Dec 23, 2013 1:31:59 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext#2b275d39: startup date [Mon Dec 23 13:31:59 CET 2013]; root of context hierarchy
Maybe somebody could help me, and tell me, what the reason for not properly auto wiring is. I tried to find this out for the last couple of hours and don't have any ideas.
Thank you very much!
You have to Annotate your HelloBean with one of the available stereotype.
Explanation of stereotypes :
#Service - Annotate all your service classes with #Service. All your
business logic will be in Service classes.
#Repository - Annotate all your DAO classes with #Repository. All
your database access logic should be in DAO classes.
#Component - Annotate your other components (for example REST
resource classes) with component stereotype.
#Autowired - Let Spring auto-wire other beans into your classes using
#Autowired annotation.
Difference
#Component – Indicates a auto scan component.
#Repository – Indicates DAO component in the persistence layer.
#Service – Indicates a Service component in the business layer.
#Controller – Indicates a controller component in the presentation layer.
Reasons to use them :
The main advantage of using #Repository or #Service over
#Component is that it's easy to write an AOP pointcut that targets,
for instance, all classes annotated with #Repository.
You don't have to write bean definitions in context xml file. Instead
annotate classes and use those by autowiring.
Specialized annotations help to clearly demarcate application layers
(in a standard 3 tiers application).
Also
<context:component-scan base-package="de.dijon.test"/>
In your test, change the name of the property from obj to helloBean
If you are using maven in your project you should store the configuration file in the classpath according the maven project structure
src/test/resources/application-context.xml
then change your #ContextConfiguration annotation to
#ContextConfiguration("/application-context.xml")
and run the test again.
Your configuration file can not be resolved because src/main/webapp/WEB-INF folder is not in the classpath by default, the configuration file is a file system file or a project file so you should reference it as is
#ContextConfiguration("file:src/main/webapp/WEB-INF/application-context.xml")
Use
<context:component-scan base-package="de.dijon.test.*"
annotation-config="true" use-default-filters="true" />
in application-context.xml file

Suddenly my spring.xml won't instantiate my classes and Error Exception occurs

I encountered a weird error that I could not understand... When I run my web project... My jsp displayed. But after clicking the submit bottom, it hangs then error results. I could not understand what I do wrong.. it is like 3hours trying to check my problem. But right now i need some help.. Thanks guys.
Unable to instantiate Action, lotmovement.action.RegisterAction, defined for 'register' in namespace '/'Error creating bean with name 'registeraction' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [lotmovement.action.RegisterAction]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registeraction' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [lotmovement.action.RegisterAction]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registeraction' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [lotmovement.action.RegisterAction]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registeraction' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [lotmovement.action.RegisterAction]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registeraction' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [lotmovement.action.RegisterAction]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registeraction' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [lotmovement.action.RegisterAction]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registeraction' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [lotmovement.action.RegisterAction]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registeraction' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [lotmovement.action.RegisterAction]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [spring.xml]; nested exception is java.lang.StackOverflowError
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:115)
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
java.security.AccessController.doPrivileged(Native Method)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
lotmovement.action.RegisterAction.<init>(RegisterAction.java:27)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:525)
java.lang.Class.newInstance0(Class.java:372)
java.lang.Class.newInstance(Class.java:325)
com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:131)
com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:162)
com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:121)
com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:300)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:400)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:501)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:432)
And on the tomcat server, this keeps on repeating..
Nov 26, 2012 3:10:51 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2d43b35f: defining beans [userprofile,registeraction,insertuserprofile,entitystart,recordexistuserprofile]; root of factory hierarchy
Nov 26, 2012 3:10:51 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#50016db: defining beans [userprofile,registeraction,insertuserprofile,entitystart,recordexistuserprofile]; root of factory hierarchy
Nov 26, 2012 3:10:51 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7ef1277f: defining beans [userprofile,registeraction,insertuserprofile,entitystart,recordexistuserprofile]; root of factory hierarchy
Nov 26, 2012 3:10:51 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#3d510eb6: defining beans [userprofile,registeraction,insertuserprofile,entitystart,recordexistuserprofile]; root of factory hierarchy
Nov 26, 2012 3:10:51 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#66893099: defining beans [userprofile,registeraction,insertuserprofile,entitystart,recordexistuserprofile]; root of factory hierarchy
Nov 26, 2012 3:17:59 PM org.apache.catalina.startup.HostConfig checkResources
INFO: Undeploying context [/LotMovement_5spingtest]
This is my XML file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="userprofile" class="lotmovement.business.entity.UserProfile">
</bean>
<bean id="registeraction" class="lotmovement.action.RegisterAction">
</bean>
<bean id="insertuserprofile"
class="lotmovement.business.crud.InsertUserProfile">
</bean>
<bean id="entitystart"
class="lotmovement.business.crud.EntityStart">
</bean>
<bean id="recordexistuserprofile"
class="lotmovement.business.crud.RecordExistUserProfile">
</bean>
</beans>
This is my some of my code..
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.action;
import com.opensymphony.xwork2.ActionSupport;
import lotmovement.business.crud.EntityStart;
import lotmovement.business.crud.InsertUserProfile;
import lotmovement.business.crud.RecordExistUserProfile;
import lotmovement.business.entity.UserProfile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* #author god-gavedmework
*/
public class RegisterAction extends ActionSupport {
private static String userId;
private static String password;
private static String firstName;
private static String lastName;
private static int securityLevel;
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
EntityStart es = (EntityStart) context.getBean("entitystart");
#Override
public void validate() {
es.StartDbaseConnection();
RecordExistUserProfile reup =
(RecordExistUserProfile) context.getBean("recordexistuserprofile");
if (reup.checkrecordexist()) {
addActionError("record already exist.");
}
}
#Override
public String execute() {
InsertUserProfile iup =
(InsertUserProfile) context.getBean("insertuserprofile");
iup.Insert();
return SUCCESS;
}
This is my WEB.XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>register.jsp</welcome-file>
</welcome-file-list>
</web-app>
You are creating an infinite loop with this line in RegisterAction
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
The loop is you invoke the Spring Container, which creates a RegisterAction, which (shown above) creates a Spring Container, which creates a RegisterAction....
You shouldn't be referencing an ApplicationContext directly in your Spring Beans. You should use configuration (setter or constructor injection) to set the dependencies of your beans. You need to do this
spring.xml
<bean id="insertUserProfile" class="lotmovement.business.crud.InsertUserProfile"/>
<bean id="registeraction" class="lotmovement.action.RegisterAction">
<property name="insertUserProfile" ref="insertUserProfile"/>
</bean>
Then you will add a method setInsertUserProfile to your RegisterAction. Spring will invoke the setter with the specified bean from your context (in this case, a new insertUserProfile). You will need to do this for all of the beans that you are referencing from the context.
You might want to do some research on Spring constructor injection as it's a "better" way of injecting dependencies that never need to change.
jeff's answer is spot on. It's a great explanation of what's wrong and what you should not be doing.
The piece you're missing is to register the application context in your web.xml:
Loading context in Spring using web.xml
This is the correction that, coupled with jeff's recommendation, should have you on your way.
Why are you handling the Spring container yourself when you are using Struts 2? You need the Struts 2 Spring plugin.
http://struts.apache.org/2.3.4.1/docs/spring-plugin.html
While the other answers are good and describe perfectly what is wrong with this code, I'm not sure they are the best answer . . . Struts 2 provides Spring integration that is EXACTLY designed to allow you to seamlessly inject dependencies into both your own objects and the core framework objects, such as actions.
With the Spring plugin, you can simply configure your spring beans, with XML or annotations, and that's that. The Spring container is integrated into the framework's core object factory, which means you don't have to handle it; and it's the handling of the container in this question's code that creates the problem for toksis.

Categories