Cannot Declare Beans inside ApplicationContext.xml - java

Whoever answers correct will be rewarded
My Implementation is as follows:
NextShipmentDaoImpl.java
public class NextShipmentDaoImpl implements NextShipmentDao{
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
LoginController.java
#Controller
public class LoginController {
#Autowired
private NextShipmentDao nextShipmentDao;
public void setNextShipmentDao(NextShipmentDao nextShipmentDao) {
this.nextShipmentDao = nextShipmentDao;
}
While Creating the required above bean like this:
<bean id="nextShipmentDao" class="com.ibrahim.dao.NextShipmentDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
ApplicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd">
<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/board" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="nextShipmentDao" class="com.ibrahim.dao.NextShipmentDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<security:http auto-config="true" >
<security:intercept-url pattern="/index*" access="ROLE_USER" />
<security:form-login login-page="/login.htm" default-target-url="/index.htm"
authentication-failure-url="/loginerror.htm" />
<security:logout logout-success-url="/logout.htm" />
</security:http>
<context:component-scan base-package="com.ibrahim.controller,com.ibrahim.domain,com.ibrahim.dao" />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Everything works fine. But when I try to create a bean This shows the error
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ibrahim.dao.NextShipmentDao com.ibrahim.controller.LoginController.nextShipmentDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nextShipmentDao' defined in ServletContext resource [/WEB-INF/board-dao.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ibrahim.dao.NextShipmentDaoImpl]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
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:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
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.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4728)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5166)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ibrahim.dao.NextShipmentDao com.ibrahim.controller.LoginController.nextShipmentDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nextShipmentDao' defined in ServletContext resource [/WEB-INF/board-dao.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ibrahim.dao.NextShipmentDaoImpl]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 22 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nextShipmentDao' defined in ServletContext resource [/WEB-INF/board-dao.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ibrahim.dao.NextShipmentDaoImpl]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1007)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
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:486)
... 24 more
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ibrahim.dao.NextShipmentDaoImpl]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1000)
... 35 more
Caused by: java.lang.IllegalArgumentException: Property 'dataSource' is required
at org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:134)
at org.springframework.jdbc.core.JdbcTemplate.<init>(JdbcTemplate.java:165)
at com.ibrahim.dao.NextShipmentDaoImpl.<init>(NextShipmentDaoImpl.java:28)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 37 more
May 07, 2015 12:21:48 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
May 07, 2015 12:21:48 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/13.1SecuringUrlAcces] startup failed due to previous errors
May 07, 2015 12:21:48 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
May 07, 2015 12:21:48 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
May 07, 2015 12:21:48 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
May 07, 2015 12:21:48 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 12402 ms
Here's My NextShipmentDaoImpl.java
public class NextShipmentDaoImpl implements NextShipmentDao{
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
JdbcTemplate jdbcTemplate= new JdbcTemplate(dataSource);
#Override
public List<NextShipment> display() {
String sql = "SELECT * FROM NEXTSHIPMENT";
List<NextShipment> shipments = new ArrayList<NextShipment>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
for (Map row : rows) {
NextShipment shipment = new NextShipment();
shipment.setOid((String) row.get("OID"));
shipment.setAddress((String) row.get("ADDRESS"));
shipment.setPack_Date((Date) row.get("PACK_DATE"));
shipment.setIsAvailable((Boolean) row.get("ISAVAILABLE"));
shipment.setAssignShipper((String) row.get("ASSIGNSHIPPER"));
shipment.setInTransit((Boolean) row.get("InTransit"));
shipments.add(shipment);
}
return shipments;
}
}

The times of the XML-based configuration are over.
I strongly recommend you to use Annotated Configuration
Something like this:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = "com.myapp.*")
public class AppConfiguration extends WebMvcConfigurerAdapter {
#Bean
public DataSource myDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("<full.driver.class.name>");
dataSource.setUrl("url");
dataSource.setUsername("dit");
dataSource.setPassword("pass");
return dataSource;
}
[...] other Beans like TransactionManager....
}

The stacktrace says :
you correctly autowire nextShipmentDAO in loginController
but dataSource property is null is the NextShipmentDAOImpl bean
and the exception occurs in JdbcTemplate initialization
The NextShipmentDAOImpl gives the cause : you correctly inject the datasource, but initialize the JdbcTemplate at construction time. So here is what happens :
jvm creates a NextShipmentDaoImpl object
jvm initializes all fields of the object including jdbcTemplate
spring sets the datasource field ... too late !
[It had been noted in comments by #M.Deinum, but I did not give it enough attention]
You shall never use an injected field at creation time, because at that moment it has not been injected. You should instead use an initialization method called by spring after all properties have been set :
public class NextShipmentDaoImpl implements NextShipmentDao{
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
JdbcTemplate jdbcTemplate;
void init(void) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
and declare the bean that way :
<bean id="nextShipmentDao" class="com.ibrahim.dao.NextShipmentDaoImpl"
init-method="init">
<property name="dataSource" ref="dataSource"></property>
</bean>

NextShipmentDaoImpl.java looks like this
public class NextShipmentDaoImpl implements NextShipmentDao{
private DataSource dataSource;
JdbcTemplate jdbcTemplate;
public NextShipmentDaoImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
In the above lines of code I had declared JdbcTemplate inside its implementation function itself. Where it is used.
And the relevant bean I had declared is:
<bean id="nextShipmentDao" class="com.ibrahim.dao.NextShipmentDaoImpl">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
LoginController remains the same:
#Controller
public class LoginController {
#Autowired
private NextShipmentDao nextShipmentDao;
public void setNextShipmentDao(NextShipmentDao nextShipmentDao) {
this.nextShipmentDao = nextShipmentDao;
}
I had shifted my spring and spring security jars from 3.2.4 to 3.2.7
Problem got solved in this manner.

Related

NoClassDefFoundExpetion: javax/persistence/PersistenceContext Spring ORM with Hibernate

I'm new to spring. I.m learning spring from javapoint. After learning some basics of spring from javapoint and spring docs, I moved towards learning hibernate with spring, but in very first try (example), I stucked with the expception: NoClassDefFoundExpetion: javax/persistence/PersistenceContext. To resolve this exception, I've googled and looked for similar kind of situations (and their solutions) on this and this, but nothing helps me.
Here is the full stacktrace: of my exception
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/PersistenceContext
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1105)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
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:202)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:207)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:697)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:526)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at test.Test.main(Test.java:15)
Caused by: java.lang.NoClassDefFoundError: javax/persistence/PersistenceContext
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.<clinit>(PersistenceAnnotationBeanPostProcessor.java:172)
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:1098)
... 12 more
I'm using eclipse-neon IDE, spring-framework 4.3.2 RELEASE, Hibernate-5.2.2 Final and Oracle 10G(database).There is a STUDENT table in my database having 4-5 entries. Also I've written thespring code using simple (console base) java project and NOT using any build tool. Here is my complete code and libraries list which I'm currently using:
Student.java
public class Student {
private Integer rollNo;
private String name;
/**
* #param rollNo
* #param name
*/
public Student(Integer rollNo, String name) {
super();
this.rollNo = rollNo;
this.name = name;
}
//Getter and setter ....
StudentDAO.java
public class StudentDAO {
private HibernateTemplate hibernateTemplate;
public StudentDAO(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate template) {
this.hibernateTemplate = template;
}
public void saveStudent(Student student) {
hibernateTemplate.save(student);
}
public List<Student> readAll() {
return hibernateTemplate.loadAll(Student.class);
}
}
I'm using java annotation based configuration, So my AppConfig.java is:
#Configuration
public class AppConfig {
#Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource("jdbc:oracle:thin:#localhost:1521/xe", "user", "password");
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactoryBean() {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
bean.setDataSource(dataSource());
bean.setMappingResources("xml/student.hbm.xml");
Properties prop = new Properties();
prop.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle9Dialect");
prop.setProperty("hibernate.hbm2ddl.auto", "update");
prop.setProperty("hibernate.show_sql", "true");
bean.setHibernateProperties(prop);
return bean;
}
#Bean
public HibernateTemplate hibernateTemplate() {
HibernateTemplate template = new HibernateTemplate((SessionFactory) sessionFactoryBean());
return template;
}
#Bean
public StudentDAO DAO() {
return new StudentDAO(hibernateTemplate());
}
}
Student.hbm.xml XML file:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="bean.Student" table="student">
<rollNo name="rollNo">
<generator class="assigned"></generator>
</rollNo>
<property name="name"></property>
</class>
</hibernate-mapping>
and here is my Main-Method Class
public class Test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
StudentDAO dao = context.getBean(StudentDAO.class);
List<Student> list = dao.readAll();
for(Student s: list)
System.out.println(s);
}
}
here is the list of liberaries (with jar file) which I've included in my project:
SPRING
HIBERNATE
Commons logging and ORALCE 10G Driver
And some other too
How to solve the above mentioned exception, which library I've to add/remove or what else I can try to resolve the issue.
Regret for long question
Example Reference
This example is based on source code, available at javapoint
I made slightly changes in my example. Instead of AppConfig.java, I used ApplicationContext.xml. Here is code for 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" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="username" value="sachin"></property>
<property name="password" value="sachin476"></property>
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>student.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect
</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="bean.dao.StudentDao">
<property name="template" ref="template"></property>
</bean>
</beans>
and added two more jar files:
>commons-dbcp2-2.1.1.jar
>commons-pool2-2.4.2.jar
for BasicDataSource class.
Now It gives me Exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mysessionFactory' defined in class path resource [xml/ApplicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
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:757)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.Test.main(Test.java:15)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/SessionFactory
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetPublicMethods(Class.java:2902)
at java.lang.Class.getMethods(Class.java:1615)
at org.springframework.beans.ExtendedBeanInfoFactory.supports(ExtendedBeanInfoFactory.java:54)
at org.springframework.beans.ExtendedBeanInfoFactory.getBeanInfo(ExtendedBeanInfoFactory.java:46)
at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:270)
at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:189)
at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:173)
at org.springframework.beans.BeanWrapperImpl.getLocalPropertyHandler(BeanWrapperImpl.java:226)
at org.springframework.beans.BeanWrapperImpl.getLocalPropertyHandler(BeanWrapperImpl.java:63)
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyHandler(AbstractNestablePropertyAccessor.java:725)
at org.springframework.beans.AbstractNestablePropertyAccessor.isWritableProperty(AbstractNestablePropertyAccessor.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1483)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
... 11 more
But I peeped into hibernate-core-5.2.2-Final.jar, that had definition for SessionFectory.class in org.hibernate package i.e there was class entry named org.hibernate.SessionFactory.class. Now I'm wondering why it gives such exceptions
UPDATE
After lots of try and search on google, I found that hibernate 5 doesn't support oracle10g drivers. so I've updated ojdbc14.jar to ojdbc6.jar, and it works for me
As mentioned here Upgrade your hibernate jpa-jar since the jpa supported version for hibernate4.3+ is 2.1.

Spring-MVC - Error creating bean with name 'procesarController': Injection of autowired dependencies failed

I am having a problem with spring , when launching the app in the server I have this error message, please help Thanks in advance!!.
Error Message
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'procesarController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.zonagifts.web.service.TransaccionService com.zonagifts.web.controller.ProcesarController.transaccionService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'TransaccionService' defined in file [C:\Users\Adolfo\Desktop\ZonacardEstableciemiento\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Webzonagifts\WEB-INF\classes\com\zonagifts\web\service\TransaccionServiceImpl.class]: Post-processing failed of bean type [class com.zonagifts.web.service.TransaccionServiceImpl] failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.zonagifts.web.service.TransaccionServiceImpl] for resource metadata: could not find class that it depends on
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779) [catalina.jar:7.0.27]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273) [catalina.jar:7.0.27]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.27]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566) [catalina.jar:7.0.27]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556) [catalina.jar:7.0.27]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_75]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_75]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_75]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_75]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.zonagifts.web.service.TransaccionService com.zonagifts.web.controller.ProcesarController.transaccionService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'TransaccionService' defined in file [C:\Users\Adolfo\Desktop\ZonacardEstableciemiento\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Webzonagifts\WEB-INF\classes\com\zonagifts\web\service\TransaccionServiceImpl.class]: Post-processing failed of bean type [class com.zonagifts.web.service.TransaccionServiceImpl] failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.zonagifts.web.service.TransaccionServiceImpl] for resource metadata: could not find class that it depends on
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 22 common frames omitted
My servlet.xml is
<?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:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<context:component-scan base-package="com.zonagifts.web" >
<context:include-filter type="aspectj" expression="com.zonagifts.*"/>
</context:component-scan>
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" cache-period="604800" />
<mvc:view-controller path="/error" view-name="error" />
<bean id="viewResolver1" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="1" />
<property name="prefix" value="/WEB-INF/jsp/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean name="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="es" />
</bean>
</beans>
My controller is
package com.zonagifts.web.controller;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zonagifts.web.domain.ResponseServicio;
import com.zonagifts.web.domain.Usuario;
import com.zonagifts.web.service.TransaccionService;
import com.zonagifts.web.util.Constantes;
#Controller
#RequestMapping("procesar")
public class ProcesarController {
#Autowired
private TransaccionService transaccionService;
private static Logger log = Logger.getLogger(LoginController.class);
#RequestMapping(value="activar",method=RequestMethod.POST)
public #ResponseBody ResponseServicio activarTarjeta(HttpSession sesion,String numeroTarjeta){
ResponseServicio responseServicio=new ResponseServicio();
Usuario usuario=(Usuario) sesion.getAttribute(Constantes.SESION_USUARIO_ZONA_CARDS);
if(usuario != null){
String [] respuesta=transaccionService.activarTarjeta(numeroTarjeta, usuario.getCodigoComercio(), usuario.getCodigoTerminal(), Constantes.TRANSACCION);
responseServicio.setRespuesta(respuesta[0]);
responseServicio.setCodigoOperacion(respuesta[1]);
responseServicio.setMensaje(respuesta[2]);
}
return responseServicio;
}
#RequestMapping(value="anular",method=RequestMethod.POST)
public #ResponseBody ResponseServicio anular(HttpSession sesion,String numeroTarjeta){
ResponseServicio responseServicio=new ResponseServicio();
Usuario usuario=(Usuario) sesion.getAttribute(Constantes.SESION_USUARIO_ZONA_CARDS);
if(usuario != null){
String [] respuesta=transaccionService.anularTarjeta(numeroTarjeta, usuario.getCodigoComercio(), usuario.getCodigoTerminal(), Constantes.TRANSACCION);
responseServicio.setRespuesta(respuesta[0]);
responseServicio.setCodigoOperacion(respuesta[1]);
responseServicio.setMensaje(respuesta[2]);
}
return responseServicio;
}
#RequestMapping(value="consumo",method=RequestMethod.POST)
public #ResponseBody ResponseServicio consumo(HttpSession sesion,String numeroTarjeta,String codigoSeguridad,String monto){
ResponseServicio responseServicio=new ResponseServicio();
Usuario usuario=(Usuario) sesion.getAttribute(Constantes.SESION_USUARIO_ZONA_CARDS);
if(usuario != null){
String [] respuesta=transaccionService.consumirSaldo(numeroTarjeta, codigoSeguridad, usuario.getCodigoComercio(), usuario.getCodigoTerminal(), monto, Constantes.TRANSACCION);
responseServicio.setRespuesta(respuesta[0]);
responseServicio.setCodigoOperacion(respuesta[1]);
responseServicio.setMensaje(respuesta[2]);
//responseServicio.setIdTransaccion(respuesta[3]);
}
return responseServicio;
}
#RequestMapping(value="saldo",method=RequestMethod.POST)
public #ResponseBody ResponseServicio saldo(HttpSession sesion,String numeroTarjeta){
ResponseServicio responseServicio=new ResponseServicio();
Usuario usuario=(Usuario) sesion.getAttribute(Constantes.SESION_USUARIO_ZONA_CARDS);
if(usuario != null){
String [] respuesta=transaccionService.consultarSaldo(numeroTarjeta, usuario.getCodigoComercio(), usuario.getCodigoTerminal(), Constantes.TRANSACCION);
responseServicio.setRespuesta(respuesta[0]);
responseServicio.setCodigoOperacion(respuesta[1]);
responseServicio.setMensaje(respuesta[2]);
}
return responseServicio;
}
}
TransactionServiceImpl
package com.zonagifts.web.service;
import java.rmi.RemoteException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.tempuri.GiftCardsSoapProxy;
import com.zonagifts.api.util.Util;
import com.zonagifts.web.controller.LoginController;
#Service
public class TransaccionServiceImpl implements TransaccionService {
private static GiftCardsSoapProxy giftCardsSoapProxy;
private static Logger log = Logger.getLogger(LoginController.class);
public String[] activarTarjeta(String numeroTarjeta, String codigoComercio,
String codigoTerminal, String idTransaccion) {
String token =tarjeta.concat(comercio).concat(terminal).concat(transaccion).concat(pass);
Object response=null;
try {
giftCardsSoapProxy=new GiftCardsSoapProxy();
response = giftCardsSoapProxy.activar_tarjeta(numeroTarjeta.trim(),
codigoComercio.trim(), codigoTerminal.trim(),
idTransaccion.trim(), token);
} catch (RemoteException e) {
e.printStackTrace();
}
String[] res = (String[]) response;
return res ;
}
public String[] anularTarjeta(String numeroTarjeta, String codigoComercio,
String codigoTerminal, String idTransaccion) {
String token =tarjeta.concat(comercio).concat(terminal).concat(transaccion).concat(pass);
Object response=null;
try {
giftCardsSoapProxy=new GiftCardsSoapProxy();
response = giftCardsSoapProxy.anular_tarjeta(numeroTarjeta.trim(),
codigoComercio.trim(), codigoTerminal.trim(),
idTransaccion.trim(), token);
} catch (RemoteException e) {
e.printStackTrace();
}
String[] res = (String[]) response;
//guardarTransaccionBD(tx);
return res ;
}
public String[] consumirSaldo(String numeroTarjeta, String codigoSeguridad,
String codigoComercio, String codigoTerminal, String montoConsumir,
String idTransaccion) {
String token =tarjeta.concat(codSeguridad).concat(comercio).concat(terminal).concat(monto).concat(transaccion).concat(pass);
Object response=null;
try {
giftCardsSoapProxy=new GiftCardsSoapProxy();
response = giftCardsSoapProxy.consumir_tarjeta(numeroTarjeta.trim(),
codigoSeguridad.trim(),codigoComercio.trim(),
codigoTerminal.trim(),montoConsumir.trim(), idTransaccion.trim(), token);
} catch (RemoteException e) {
e.printStackTrace();
}
String[] res = (String[]) response;
return res ;
}
public String[] consultarSaldo(String numeroTarjeta, String codigoComercio,
String codigoTerminal, String idTransaccion) {
String token =tarjeta.concat(comercio).concat(terminal).concat(transaccion).concat(pass);
Object response=null;
try {
giftCardsSoapProxy=new GiftCardsSoapProxy();
response = giftCardsSoapProxy.consultar_saldo(numeroTarjeta.trim(),
codigoComercio.trim(), codigoTerminal.trim(),
idTransaccion.trim(), token);
} catch (RemoteException e) {
e.printStackTrace();
}
String[] res = (String[]) response;
return res ;
}
}
TransaccionService
package com.zonagifts.web.service;
public interface TransaccionService {
String[] activarTarjeta(String numeroTarjeta,String codigoComercio,String codigoTerminal,String idTransaccion);
String[] anularTarjeta(String numeroTarjeta,String codigoComercio,String codigoTerminal,String idTransaccion);
String[] consumirSaldo(String numeroTarjeta,String codigoSeguridad,String codigoComercio,String codigoTerminal,String montoConsumir,String idTransaccion);
String[] consultarSaldo(String numeroTarjeta,String codigoComercio,String codigoTerminal,String idTransaccion);
}
So the final exception that you get is the following:
java.lang.IllegalStateException: Failed to introspect bean class [com.zonagifts.web.service.TransaccionServiceImpl] for resource metadata: could not find class that it depends on
Looking at your TransaccionServiceImpl class, there are a few things that could be missing from your class path...
org.tempuri.GiftCardsSoapProxy
com.zonagifts.web.controller.LoginController
There are others, but these are the two that give me the most pause.
Could you verify that these two files (or their jar files) are in your deployed classpath?
After looking at your My servlet.xml I found that you didn't have the context:annotation-config tag. As you are using annotations to wire your beans you need to have this tag in your xml.
<context:annotation-config></context:annotation-config>
As there is a single Implementation for the interface and the component scanning is turned on, I don't think you will need to qualify the bean. But if app doesn't work even after adding the context:annotation-config tag, try to qualify the bean. You can qualify as follows
Annotate the TransaccionServiceImpl class with #service("transaccionServiceImplBean") and when you wire it in ProcesarController provide the qualifier as below
#Autowired
#Qualifier("transaccionServiceImplBean")
private TransaccionService transaccionService;

Error while creating bean: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError

I am facing the following error when I try to create bean using Application Context for the circle class! Circle class implements the Shape interface which contains a method draw().
Configuration:
I am learning spring and have setup a Java Project in eclipse with all the required jars (Spring and Apache commons logging). I have the spring.xml in my classpath in the src folder. Have also tried downloading the latest jars (Spring 4.0.4 release, previously worked with 4.0.0) but now is not working. Cannot think of any solution to fix this.
Error:
May 11, 2014 6:20:50 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#90832e: startup date [Sun May 11 18:20:50 EDT 2014]; root of context hierarchy
May 11, 2014 6:20:50 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor': Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:88)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.springApplication.DrawingApplication.main(DrawingApplication.java:16)
Caused by: java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1071)
... 13 more
Caused by: java.lang.NullPointerException
at org.springframework.beans.PropertyEditorRegistrySupport.<clinit>(PropertyEditorRegistrySupport.java:92)
... 14 more
DrawingApplication.java
package com.springApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApplication {
public static void main(String[] args) {
//The beanFactory reads from an XML file
//BeanFactory context = new XmlBeanFactory(new FileSystemResource("spring.xml"));
//Application Context provides -- Event notification and more than Bean Factory
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//Here we pass the id of the bean from the XML given in the above line
Shape shape = (Shape)context.getBean("circle");
//Calling the draw method through object local object created using Spring
shape.draw();
}
}
Circle.java
package com.springApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Circle implements Shape{
private Point center;
public Point getCenter() {
return center;
}
#Autowired
#Qualifier("circleRelated")
public void setCenter(Point center) {
this.center = center;
}
#Override
public void draw() {
System.out.println("Drawing a Circle");
System.out.println("Center Point is: (" + center.getX() + ", " + center.getY() + ")");
}
}
Point.java
package com.springApplication;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
spring.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:context="http://www.springframework.org/schema/context"
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">
<bean id="pointA" class="com.springApplication.Point">
<qualifier value="circleRelated" />
<property name="x" value="0"/>
<property name="y" value="0"/>
</bean>
<bean id="PointB" class="com.springApplication.Point">
<property name="x" value="0"/>
<property name="y" value="20"/>
</bean>
<bean id="PointC" class="com.springApplication.Point">
<property name="x" value="-20"/>
<property name="y" value="0"/>
</bean>
<bean id="circle" class="com.springApplication.Circle">
</bean>
<!-- <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> -->
<context:annotation-config/>
</beans>
Please let me know if anything else is needed. Someone please help !
Sorry about the wrong placing!!
#Andrei Stefan
List of Jars ---------
commons-logging-1.1.3
spring-aop-4.0.4.RELEASE
spring-aop-4.0.4.RELEASE-javadoc
spring-aop-4.0.4.RELEASE-sources
spring-aspects-4.0.4.RELEASE
spring-aspects-4.0.4.RELEASE-javadoc
spring-aspects-4.0.4.RELEASE-sources
spring-beans-4.0.4.RELEASE
spring-beans-4.0.4.RELEASE-javadoc
spring-beans-4.0.4.RELEASE-sources
spring-build-src-4.0.4.RELEASE
spring-context-4.0.4.RELEASE
spring-context-4.0.4.RELEASE-javadoc
spring-context-4.0.4.RELEASE-sources
spring-context-support-4.0.4.RELEASE
spring-context-support-4.0.4.RELEASE-javadoc
spring-context-support-4.0.4.RELEASE-sources
spring-core-4.0.4.RELEASE
spring-core-4.0.4.RELEASE-javadoc
spring-core-4.0.4.RELEASE-sources
spring-expression-4.0.4.RELEASE
spring-expression-4.0.4.RELEASE-javadoc
spring-expression-4.0.4.RELEASE-sources
spring-framework-bom-4.0.4.RELEASE
spring-framework-bom-4.0.4.RELEASE-javadoc
spring-framework-bom-4.0.4.RELEASE-sources
spring-instrument-4.0.4.RELEASE
spring-instrument-4.0.4.RELEASE-javadoc
spring-instrument-4.0.4.RELEASE-sources
spring-instrument-tomcat-4.0.4.RELEASE
spring-instrument-tomcat-4.0.4.RELEASE-javadoc
spring-instrument-tomcat-4.0.4.RELEASE-sources
spring-jdbc-4.0.4.RELEASE
spring-jdbc-4.0.4.RELEASE-javadoc
spring-jdbc-4.0.4.RELEASE-sources
spring-jms-4.0.4.RELEASE
spring-jms-4.0.4.RELEASE-javadoc
spring-jms-4.0.4.RELEASE-sources
spring-messaging-4.0.4.RELEASE
spring-messaging-4.0.4.RELEASE-javadoc
spring-messaging-4.0.4.RELEASE-sources
spring-orm-4.0.4.RELEASE
spring-orm-4.0.4.RELEASE-javadoc
spring-orm-4.0.4.RELEASE-sources
spring-oxm-4.0.4.RELEASE
spring-oxm-4.0.4.RELEASE-javadoc
spring-oxm-4.0.4.RELEASE-sources
spring-test-4.0.4.RELEASE
spring-test-4.0.4.RELEASE-javadoc
spring-test-4.0.4.RELEASE-sources
spring-tx-4.0.4.RELEASE
spring-tx-4.0.4.RELEASE-javadoc
spring-tx-4.0.4.RELEASE-sources
spring-web-4.0.4.RELEASE
spring-web-4.0.4.RELEASE-javadoc
spring-web-4.0.4.RELEASE-sources
spring-webmvc-4.0.4.RELEASE
spring-webmvc-4.0.4.RELEASE-javadoc
spring-webmvc-4.0.4.RELEASE-sources
spring-webmvc-portlet-4.0.4.RELEASE
spring-webmvc-portlet-4.0.4.RELEASE-javadoc
spring-webmvc-portlet-4.0.4.RELEASE-sources
spring-websocket-4.0.4.RELEASE
spring-websocket-4.0.4.RELEASE-javadoc
spring-websocket-4.0.4.RELEASE-sources
All of these plus other default system libraries are referenced.
The problem occurs because
PropertyEditorRegistrySupport.class.getClassLoader()
is null. According to JavaDoc, this happens if the class PropertyEditorRegistrySupport has been loaded by the bootstrap class loader instead of the system class loader:
Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.
Perhaps your Spring libraries are on the endorsed class path?

Spring 3.2.x: Integration test fails when injecting concrete bean

Spring 3.2.6-RELEASE and JUnit 4.11
I've being trying to write integration tests with spring 3.2.6-RELEASE and for some reason my bean can't be injected into the test class.
When I remove the extends AbstractSpringService part the code works fine. But it would be a shame to loose all the reusable code in my AbstractSpringService.
The code also works when I remove the persistance part of the configuration file leaving only this:
<context:property-placeholder location="classpath*:*.properties"/>
<context:annotation-config/>
<context:component-scan base-package="br.eti.danielcamargo.hsnpersonal.model" />
Any idea of what is going on here?
Here is the service to test:
import br.eti.danielcamargo.hsnpersonal.domain.entities.Programa;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
#Service
public class ProgramaService extends AbstractSpringService<Programa> {
#PersistenceContext
private EntityManager em;
#PostConstruct
private void setup() {
System.out.println("Creating programaService");
}
public ProgramaService() {
super(Programa.class);
}
#Override
public EntityManager getEntityManager() {
return em;
}
}
It's parent:
import br.eti.danielcamargo.commons.business.AbstractService;
import br.eti.danielcamargo.commons.business.BusinessException;
import br.eti.danielcamargo.commons.domain.AbstractEntity;
import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractSpringService<ENTITY extends AbstractEntity> extends AbstractService<ENTITY> {
public AbstractSpringService(Class<ENTITY> entityClass) {
super(entityClass);
}
#Override
#Transactional
public ENTITY save(ENTITY entity) throws BusinessException {
return super.save(entity);
}
#Override
#Transactional
public void remove(ENTITY entity) {
super.remove(entity);
}
}
And grandparent:
import br.eti.danielcamargo.commons.domain.AbstractEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
public abstract class AbstractService<ENTITY extends AbstractEntity> implements
Serializable {
private static final long serialVersionUID = 1L;
private static final Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
public abstract EntityManager getEntityManager();
private final Class<ENTITY> entityClass;
public AbstractService(Class<ENTITY> entityClass) {
this.entityClass = entityClass;
}
public void validate(ENTITY entity) throws BusinessException {
Set<ConstraintViolation<ENTITY>> constraintViolations = validator
.validate(entity);
if (!constraintViolations.isEmpty()) {
List<ValidationOccurrence> ocorrencias = new ArrayList<ValidationOccurrence>();
for (ConstraintViolation<ENTITY> constraintViolation : constraintViolations) {
ocorrencias.add(new ValidationOccurrence(true, constraintViolation
.getRootBeanClass().getSimpleName()
+ "."
+ constraintViolation.getPropertyPath(),
constraintViolation.getMessage(), constraintViolation
.getInvalidValue()));
}
throw new BusinessException(ocorrencias);
}
}
public ENTITY save(ENTITY entity) throws BusinessException {
validate(entity);
entity = getEntityManager().merge(entity);
afterSave(entity);
return entity;
}
public void afterSave(ENTITY entity) {
}
public ENTITY get(Long id) {
TypedQuery<ENTITY> query = null;
try {
query = getEntityManager().createNamedQuery(
"get" + entityClass.getSimpleName(), entityClass);
} catch (IllegalArgumentException e) {
return getEntityManager().find(entityClass, id);
}
try {
query.setParameter("id", id);
} catch (IllegalArgumentException e) {
query.setParameter(1, id);
}
query.setMaxResults(1);
List<ENTITY> result = query.getResultList();
return result.isEmpty() ? null : result.get(0);
}
public List<ENTITY> getAll() {
TypedQuery<ENTITY> query = null;
try {
query = getEntityManager().createNamedQuery(
"getAll" + entityClass.getSimpleName(), entityClass);
} catch (IllegalArgumentException e) {
CriteriaQuery<ENTITY> cq = getEntityManager().getCriteriaBuilder()
.createQuery(entityClass);
cq.select(cq.from(entityClass));
query = getEntityManager().createQuery(cq);
}
List<ENTITY> result = query.getResultList();
return result;
}
public void remove(ENTITY entity) {
entity = getEntityManager().find(entityClass, entity.getId());
getEntityManager().remove(entity);
}
}
Here is the test:
import javax.annotation.PostConstruct;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/testContext.xml")
public class ProgramaServiceTest {
#Autowired
private ProgramaService programaService;
#PostConstruct
private void setup() {
System.out.println("Creating programa test");
}
#Test
public void test() {
Assert.assertNotNull(programaService);
}
}
And here is the configuration file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:property-placeholder location="classpath*:*.properties"/>
<context:annotation-config/>
<context:component-scan base-package="br.eti.danielcamargo.hsnpersonal.model" />
<!-- PERSISTENCE -->
<bean id="appDS" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!-- Connection properties -->
<property name="driverClass" value="${database.driverClassName}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.username}" />
<property name="password" value="${database.password}" />
<!-- Pool properties -->
<property name="minPoolSize" value="1" />
<property name="maxPoolSize" value="2" />
<property name="maxStatements" value="50" />
<property name="idleConnectionTestPeriod" value="3000" />
<property name="loginTimeout" value="300" />
</bean>
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="appDS" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="${database.persistentUnitName}" />
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.import_files">${database.imports}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Here is the exception:
[HSN-PERSONAL] [INFO]: [23:17:34,208] [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - [Loading XML bean definitions from class path resource [testContext.xml]]
[HSN-PERSONAL] [INFO]: [23:17:34,414] [org.springframework.context.support.GenericApplicationContext] - [Refreshing org.springframework.context.support.GenericApplicationContext#41942912: startup date [Mon Feb 03 23:17:34 BRST 2014]; root of context hierarchy]
[HSN-PERSONAL] [INFO]: [23:17:34,527] [org.springframework.context.support.PropertySourcesPlaceholderConfigurer] - [Loading properties file from file [D:\development\projects\hsn-personal\target\test-classes\database.properties]]
[HSN-PERSONAL] [INFO]: [23:17:34,534] [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - [JSR-330 'javax.inject.Inject' annotation found and supported for autowiring]
[HSN-PERSONAL] [INFO]: [23:17:34,603] [com.mchange.v2.log.MLog] - [MLog clients using log4j logging.]
[HSN-PERSONAL] [INFO]: [23:17:34,705] [com.mchange.v2.c3p0.C3P0Registry] - [Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10]]
[HSN-PERSONAL] [INFO]: [23:17:34,845] [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] - [Building JPA container EntityManagerFactory for persistence unit 'hsnpu']
[HSN-PERSONAL] [INFO]: [23:17:34,992] [org.hibernate.annotations.common.Version] - [HCANN000001: Hibernate Commons Annotations {4.0.2.Final}]
[HSN-PERSONAL] [INFO]: [23:17:34,998] [org.hibernate.Version] - [HHH000412: Hibernate Core {4.2.2.Final}]
[HSN-PERSONAL] [INFO]: [23:17:35,000] [org.hibernate.cfg.Environment] - [HHH000206: hibernate.properties not found]
[HSN-PERSONAL] [INFO]: [23:17:35,002] [org.hibernate.cfg.Environment] - [HHH000021: Bytecode provider name : javassist]
[HSN-PERSONAL] [INFO]: [23:17:35,023] [org.hibernate.ejb.Ejb3Configuration] - [HHH000204: Processing PersistenceUnitInfo [
name: hsnpu
...]]
[HSN-PERSONAL] [INFO]: [23:17:35,170] [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] - [HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider]
[HSN-PERSONAL] [INFO]: [23:17:35,236] [com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] - [Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge5zz8z1xhw46nud6z0y|5c07481f, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> org.postgresql.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge5zz8z1xhw46nud6z0y|5c07481f, idleConnectionTestPeriod -> 3000, initialPoolSize -> 3, jdbcUrl -> jdbc:postgresql://127.0.0.1:5432/hsn, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 2, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 1, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]]
[HSN-PERSONAL] [INFO]: [23:17:35,503] [org.hibernate.dialect.Dialect] - [HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect]
[HSN-PERSONAL] [INFO]: [23:17:35,512] [org.hibernate.engine.jdbc.internal.LobCreatorBuilder] - [HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException]
[HSN-PERSONAL] [INFO]: [23:17:35,697] [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] - [HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory]
[HSN-PERSONAL] [INFO]: [23:17:35,702] [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] - [HHH000397: Using ASTQueryTranslatorFactory]
[HSN-PERSONAL] [INFO]: [23:17:35,743] [org.hibernate.validator.internal.util.Version] - [HV000001: Hibernate Validator 4.3.1.Final]
[HSN-PERSONAL] [INFO]: [23:17:36,066] [org.hibernate.tool.hbm2ddl.SchemaExport] - [HHH000227: Running hbm2ddl schema export]
[HSN-PERSONAL] [INFO]: [23:17:39,131] [org.hibernate.tool.hbm2ddl.SchemaExport] - [HHH000230: Schema export complete]
[HSN-PERSONAL] [INFO]: [23:17:39,197] [org.springframework.beans.factory.support.DefaultListableBeanFactory] - [Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5839cb0: defining beans [org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,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,programaService,appDS,persistenceUnitManager,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy]
Creating programaService
[HSN-PERSONAL] [ERROR]: [23:17:39,251] [org.springframework.test.context.TestContextManager] - [Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#619130e2] to prepare test instance [br.eti.danielcamargo.hsnpersonal.model.services.ProgramaServiceTest#3207779]]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'br.eti.danielcamargo.hsnpersonal.model.services.ProgramaServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.eti.danielcamargo.hsnpersonal.model.services.ProgramaService br.eti.danielcamargo.hsnpersonal.model.services.ProgramaServiceTest.programaService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [br.eti.danielcamargo.hsnpersonal.model.services.ProgramaService] 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:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376)
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:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
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:174)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.eti.danielcamargo.hsnpersonal.model.services.ProgramaService br.eti.danielcamargo.hsnpersonal.model.services.ProgramaServiceTest.programaService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [br.eti.danielcamargo.hsnpersonal.model.services.ProgramaService] 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:517)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [br.eti.danielcamargo.hsnpersonal.model.services.ProgramaService] 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:988)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
... 28 more
[HSN-PERSONAL] [INFO]: [23:17:39,262] [org.springframework.context.support.GenericApplicationContext] - [Closing org.springframework.context.support.GenericApplicationContext#41942912: startup date [Mon Feb 03 23:17:34 BRST 2014]; root of context hierarchy]
[HSN-PERSONAL] [INFO]: [23:17:39,263] [org.springframework.beans.factory.support.DefaultListableBeanFactory] - [Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5839cb0: defining beans [org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,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,programaService,appDS,persistenceUnitManager,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy]
[HSN-PERSONAL] [INFO]: [23:17:39,269] [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] - [Closing JPA EntityManagerFactory for persistence unit 'hsnpu']
The problem was solved by adding
<aop:aspectj-autoproxy proxy-target-class="true" />
to the configuration file. Documentation for proxy-target-class says:
"Are class-based (CGLIB) proxies to be created? By default, standard Java interface-based proxies are created."
I suspect when Spring created this bean, it is of the parent class type, not subclass. Hence when you requested to autowire the subclass, it couldn't cast it / couldn't tell this parent class has one.
It should work if you autowire using the parent class:
#Autowired private AbstractSpringService programaService;
If you do need to use the subclass' members you can cast it.
If you have multiple beans implementing the abstract, you can select a particular one by using #Qualifier
#Autowired #Qualifier("foo") private AbstractSpringService programaService;
And in your service class
#Service("foo")
public class Blah extends AbstractSpringService {
...
Other solution maybe to avoid using #Service and declare the bean in xml.
I hope there's a more elegant solution than these

Error creating bean By #Resource

I am tiring to to build a small application with spring+hibernate+maven+postgreSQL but when i am tiring to inject dependency in my controller and service class it creates problem for injecting the dependency here is the code and logs please give your suggestion to solve this wiring problem?
mvc-dispature-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:component-scan base-package="com.bms" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/bms" />
<property name="username" value="postgres" />
<property name="password" value="*******" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.bms.Domain.Book</value>
</list>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Controller class BooksEntryController.java
#Controller
#RequestMapping(value = "/dashboard/*")
public class BooksEntryController {
#Resource
private BookFormService bookFormServiceImp;
#RequestMapping(value = "/booksentryform", method = RequestMethod.GET)
public ModelAndView viewBooksEntryForm(Model model) {
model.addAttribute("test", new Book());
return new ModelAndView("bookregistrationform");
}
#RequestMapping(value = "/addbookdetails", method = RequestMethod.POST)
public String addBook(#ModelAttribute("test") Book book, Model model) {
if (book != null) {
bookFormServiceImp.addBooks(book);
return "bookaddsuccessfully";
} else {
throw new NullPointerException();
}
}
}
Service interface BookFormService.java
public interface BookFormService {
void addBooks(Book book);
}
ServiceImp class BookFormServiceImp.java
#Service("bookFormServiceImp")
public class BookFormServiceImp implements BookFormService {
#Resource
private BookFormDao bookFormDaoImp ;
public void addBooks(Book book) {
bookFormDaoImp.addBook(book);
// TODO Auto-generated method stub
}
}
Dao interface BookFormDao .java
public interface BookFormDao {
public void addBook(Book book); }
DaoImp class BookFormDaoImp.java
#Repository("bookFormDaoImp")
public class BookFormDaoImp implements BookFormDao {
#Resource
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addBook(Book book) {
// TODO Auto-generated method stub
getCurrentSession().save(book);
}
}
Here is the log :
2013-06-20 00:35:51.528:INFO:/bms:Initializing Spring root WebApplicationContext
Jun 20, 2013 12:35:51 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Jun 20, 2013 12:35:51 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Thu Jun 20 00:35:51 IST 2013]; root of context hierarchy
Jun 20, 2013 12:35:51 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
Jun 20, 2013 12:35:52 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2df8f8: defining beans [booksEntryController,bookFormDaoImp,bookFormServiceImp,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.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Jun 20, 2013 12:35:52 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2df8f8: defining beans [booksEntryController,bookFormDaoImp,bookFormServiceImp,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.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Jun 20, 2013 12:35:52 AM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksEntryController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookFormServiceImp': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookFormDaoImp': Injection of resource dependencies failed; nested exception is java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306)
...................................
....................................
You are probably not using the right sessionFactory class. If you are using Hibernate 4, use LocalSessionFactoryBean instead of AnnotationSessionFactoryBean.
Replace
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
by
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

Categories

Resources