Junit test issue with autowiring a sessionfactory bean - spring

I am trying to implement a simple Entity's unit test for my application but i got this erro although i was trying lots of solutions
I am using Spring MVC and Hibernate.
this is my context file:
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
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"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<context:component-scan base-package="teams"/>
<context:component-scan base-package="teams.*"/>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Database connection Bean definition -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/teams" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>teams.model.Team</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
<beans:prop key="hibernate.connection.charset">UTF-8</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<!-- DAO and Service Beans definition -->
<beans:bean id="teamDAO" class="teams.dao.TeamDAOImpl">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="teamService" class="teams.service.TeamServiceImpl">
<beans:property name="teamDAO" ref="teamDAO"></beans:property>
</beans:bean>
<!-- Enabling Transaction manager -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Config Transaction Manager -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
my entity is
Team.java
package teams.model;
import javax.persistence.*;
import org.apache.commons.lang.builder.EqualsBuilder;
/**
* Entity bean with JPA annotations
* Hibernate provides JPA implementation
*
*/
#Entity
#Table(name = "teams")
public class Team {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer rating;
public Team() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
#Override
public String toString(){
return "id="+id+", name="+name+", rating="+rating;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Team == false) {
return false;
}
if (this == obj) {
return true;
}
final Team team = (Team) obj;
return new EqualsBuilder().append(id, team.getId())
.append(name, team.getName()).append(rating, team.getRating())
.isEquals();
}
}
and this the test calss of my entity:
package teams;
import java.util.List;
import junit.framework.Assert;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
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;
import teams.model.Team;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath*:/spring/servlet-context*.xml")
public class TeamTest {
static Session session;
#Autowired
public void setFactory(SessionFactory factory) {
session = factory.openSession();
}
#Test
public void testConfiguration() {
// Setup
Team team = new Team();
team.setName("Palo");
team.setRating(9);
session.beginTransaction();
// Action
team=(Team) session.merge(team);
List teams = session.createCriteria(Team.class).list();
// Test
Assert.assertEquals(1, teams.size());
Assert.assertEquals(team, teams.get(0));
}
#AfterClass
public static void tearDown(){
session.close();
}
}
this is the output of the issue:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'teams.TeamTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void teams.TeamTest.setFactory(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
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:319)
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:15)
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:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void teams.TeamTest.setFactory(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 27 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:553)
... 29 more
2017-12-11 18:06:33 DEBUG DirtiesContextTestExecutionListener:126 - After test class: context [DefaultTestContext#3e6358 testClass = TeamTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#15f7ae5 testClass = TeamTest, locations = '{classpath*:/spring/servlet-context*.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], dirtiesContext [false].
2017-12-11 18:06:33 INFO GenericApplicationContext:873 - Closing org.springframework.context.support.GenericApplicationContext#9d9c55: startup date [Mon Dec 11 18:06:33 GMT+01:00 2017]; root of context hierarchy
2017-12-11 18:06:33 DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'lifecycleProcessor'
2017-12-11 18:06:33 DEBUG DefaultListableBeanFactory:474 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#874448: defining beans [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,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; root of factory hierarchy
each time i run the test, these errors appear even that i tried to test the Dao or the controller class , but i still get the same issue.
please can you help me to solve this problem? and if there is something wrong with the code how can i correct it ?

Related

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field

I have an error when running my code.
Error message:
type Exception report
message Servlet.init() for servlet mvc-dispatcher threw exception
description The server encountered an internal error that prevented it
from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet
mvc-dispatcher threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'tipoSanguineoController': Injection of
autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
br.inf.datus.ifisio.service.TipoSanguineoService
br.inf.datus.ifisio.controller.TipoSanguineoController.tipoSanguineoService;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'tipoSanguineoServiceImpl' defined in file
[D:\projetos\ifisio\target\ifisio\WEB-INF\classes\br\inf\datus\ifisio\service\TipoSanguineoServiceImpl.class]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [br.inf.datus.ifisio.service.TipoSanguineoServiceImpl]: No
default constructor found; nested exception is
java.lang.NoSuchMethodException:
br.inf.datus.ifisio.service.TipoSanguineoServiceImpl.()
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
br.inf.datus.ifisio.service.TipoSanguineoService
br.inf.datus.ifisio.controller.TipoSanguineoController.tipoSanguineoService;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'tipoSanguineoServiceImpl' defined in file
[D:\projetos\ifisio\target\ifisio\WEB-INF\classes\br\inf\datus\ifisio\service\TipoSanguineoServiceImpl.class]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [br.inf.datus.ifisio.service.TipoSanguineoServiceImpl]: No
default constructor found; nested exception is
java.lang.NoSuchMethodException:
br.inf.datus.ifisio.service.TipoSanguineoServiceImpl.()
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
and my files:
web.xml:
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>x</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
mvc-dispatcher-servlet.xml:
<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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scan base-package="br.inf.datus.ifisio"/>
<mvc:annotation-driven/>
<!-- Database properties -->
<context:property-placeholder location="classpath:application.properties"/>
<!-- Resource location to load JS, CSS, Images etc -->
<mvc:resources mapping="/resources/**" location="/resources/"/>
<!--Prevent browsers from caching contents except the static resources content-->
<mvc:interceptors>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang"/>
</bean>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/resources/**"/>
<bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- View Resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${db.driverClassName}"/>
<property name="jdbcUrl" value="${db.url}"/>
<property name="user" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="acquireIncrement" value="${conn.acquireIncrement}"/>
<property name="minPoolSize" value="${conn.minPoolSize}"/>
<property name="maxPoolSize" value="${conn.maxPoolSize}"/>
<property name="maxIdleTime" value="${conn.maxIdleTime}"/>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<property name="packagesToScan" value="br.inf.datus.ifisio.persistence.entity"/>
</bean>
<!-- Transaction -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
GenericDaoImpl:
package br.inf.datus.ifisio.persistence.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import br.inf.datus.ifisio.persistence.dao.GenericDao;
#Repository
public abstract class GenericDaoImpl<E, K extends Serializable> implements GenericDao<E, K> {
#Autowired
private SessionFactory sessionFactory;
protected Class<? extends E> daoType;
#SuppressWarnings("unchecked")
public GenericDaoImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void add(E entity) {
currentSession().save(entity);
}
#Override
#SuppressWarnings("unchecked")
public E findById(K key) {
return (E) currentSession().get(daoType, key);
}
#Override
#SuppressWarnings("unchecked")
public List<E> getAll() {
return currentSession().createCriteria(daoType).list();
}
#Override
public void update(E entity) {
currentSession().saveOrUpdate(entity);
}
#Override
public void remove(E entity) {
currentSession().delete(entity);
}
#Override
public void saveOrUpdate(E entity) {
currentSession().saveOrUpdate(entity);
}
}
GenericServiceImpl:
package br.inf.datus.ifisio.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import br.inf.datus.ifisio.persistence.dao.GenericDao;
#Service
public abstract class GenericServiceImpl<E, K> implements GenericService<E, K> {
private GenericDao<E, K> genericDao;
public GenericServiceImpl(GenericDao<E,K> genericDao) {
this.genericDao=genericDao;
}
public GenericServiceImpl() {
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void add(E entity) {
genericDao.add(entity);
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public E findById(K id) {
return genericDao.findById(id);
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public List<E> getAll() {
return genericDao.getAll();
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void remove(E entity) {
genericDao.remove(entity);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void saveOrUpdate(E entity) {
genericDao.saveOrUpdate(entity);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void update(E entity) {
genericDao.update(entity);
}
}
TipoSanguineoDaoImpl:
package br.inf.datus.ifisio.persistence.dao;
import br.inf.datus.ifisio.persistence.entity.TipoSanguineo;
import org.springframework.stereotype.Repository;
#Repository
public class TipoSanguineoDaoImpl extends GenericDaoImpl<TipoSanguineo, Long> implements TipoSanguineoDao {
}
TipoSanguineoServiceImpl:
package br.inf.datus.ifisio.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import br.inf.datus.ifisio.persistence.dao.GenericDao;
import br.inf.datus.ifisio.persistence.dao.TipoSanguineoDao;
import br.inf.datus.ifisio.persistence.entity.TipoSanguineo;
#Service
public class TipoSanguineoServiceImpl extends GenericServiceImpl<TipoSanguineo, Long> implements TipoSanguineoService {
#Autowired
private final TipoSanguineoDao tipoSanguineoDao;
public TipoSanguineoServiceImpl(#Qualifier("tipoSanguineoDaoImpl") GenericDao<TipoSanguineo, Long> genericDao) {
super(genericDao);
this.tipoSanguineoDao = (TipoSanguineoDao) genericDao;
}
}
The answer is there in the stack trace:
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [br.inf.datus.ifisio.service.TipoSanguineoServiceImpl]: No default constructor found;
You have specified field injection in that class (#Autowired annotation on field tipoSanguineoDao) but you provided no default (no-argument) constructor. It appears that you want constructor injection (evidenced by the fact that you have a #Qualifier annotation on the constructor argument), but that conflicts with field injection.
Move the #Autowired annotation to the constructor.
Looks like you are trying to do constructor based dependency injection..
Below change in TipoSanguineoServiceImpl should correct your problem.
#Autowired
public TipoSanguineoServiceImpl(#Qualifier("tipoSanguineoDaoImpl") GenericDao<TipoSanguineo, Long> genericDao) {
super(genericDao);
this.tipoSanguineoDao = (TipoSanguineoDao) genericDao;
}

Spring Autowiring not working - BeanCreationException

I want to integrate Spring with Hibernate. I am new to both technologies. At the moment I get an error like this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public service.UserService controller.HomeController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.UserService] 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)}
Can anybody help me, please?
package controller;
#Controller
public class HomeController {
#Autowired
private UserService userService;
#RequestMapping("/register")
public ModelAndView getRegisterForm(#ModelAttribute("user") User user,
BindingResult result) {
ArrayList<String> gender = new ArrayList<String>();
gender.add("Male");
gender.add("Female");
ArrayList<String> city = new ArrayList<String>();
city.add("Delhi");
city.add("Kolkata");
city.add("Chennai");
city.add("Bangalore");
Map<String, Object> model = new HashMap<String, Object>();
model.put("gender", gender);
model.put("city", city);
System.out.println("Register Form");
return new ModelAndView("Register", "model", model);
}
#RequestMapping("/saveUser")
public ModelAndView saveUserData(#ModelAttribute("user") User user,
BindingResult result) {
userService.addUser(user);
System.out.println("Save User Data");
return new ModelAndView("redirect:/userList.html");
}
#RequestMapping("/userList")
public ModelAndView getUserList() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", userService.getUser());
return new ModelAndView("UserDetails", model);
}
}
package service;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserDao userDao;
#Override
public void addUser(User user) {
userDao.saveUser(user);
}
#Override
public List<User> getUser() {
return userDao.getUser();
}
}
spring-servlet Code:
Hi need a Spring ,Hibernate integration example for my new project.so i have copied this from a website.and i did some modifications in that ..It's not working please help me
<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"
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">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="controller" />
<tx:annotation-driven/>
<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/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="myydao" class="dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="/user/*.htm" class="controller.HomeController" >
<property name="UserDao" ref="mydao" />
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
I assume that you haven't added the bean to your Spring Application Context
If you are using xml, you need to do this by adding something like the following to the xml file:
<bean class="service.UserServiceImpl" id="userService"/>
Or, if you are using a Java based configuration class, you need to add a bean like so:
#Configuration
public class AppConfig{
#Bean
public UserService userService() {
return new UserServiceImpl();
}
}
Or, if you add the #Component annotation to UserServiceImpl and #ComponentScan("service") annotation to the Java App config, it should pick up the User service
Make sure you have enabled the component scanning to automatically detect classes and register respective beans.
You should add below entry to your bean definition XML file:
<context:component-scan base-package="org.example"/>
More about automatic bean detection

Autowiring Controller doesn't work after adding entityManagerFactory bean

I've wrote a spring mvc webserver which uses NEO4j as data backend. Now i want to expand this with cassandra, so the server should be able to use both databases.
I have followed these 2 tutorials on how to combine Kundera (A JPA based Cassandra API):
https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-Spring
https://code.google.com/p/kundera/wiki/HowToUseKunderaWithSpring
But i'm not able to add the entitymanagerfactory bean to my applicationcontext.xml file.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cassandra_pu"/>
</bean>
When i do this, spring gives an error that it can not create any of the already existing controllers that my webserver uses.
Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private bmsapp.service.DataBasePopulator bmsapp.controller.IndexController.dbPopulator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
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.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private bmsapp.service.DataBasePopulator bmsapp.controller.IndexController.dbPopulator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
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)
... 22 more
Those controllers are created by using the #Controller annotation in their class files and by autowiring them in the files where they are used. This works fine normally but when i add the entityManagerFactory bean it suddenly stops working. How is this possible?
My applicationContext file currently looks like this:
<?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:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- Scans the classpath for annotated components that will be auto-registered
as Spring beans. For example #Controller and #Service. -->
<context:component-scan base-package="bmsapp" />
<!-- Activate Spring Data Neo4j repository support -->
<neo4j:config storeDirectory="data/graph.db" base-package="bmsapp.domain" />
<neo4j:repositories base-package="bmsapp.repository" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cassandra_pu"/>
</bean>
<tx:annotation-driven mode="proxy" />
<!-- context:annotation-config / -->
<!-- use this for Spring Jackson JSON support -->
<mvc:annotation-driven />
And my persistence.xml file:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="cassandra_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<properties>
<property name="kundera.nodes" value="localhost"/>
<property name="kundera.port" value="9160"/>
<property name="kundera.keyspace" value="KunderaExamples"/>
<property name="kundera.dialect" value="cassandra"/>
<property name="kundera.client.lookup.class" value="com.impetus.client.cassandra.pelops.PelopsClientFactory" />
<property name="kundera.cache.provider.class" value="com.impetus.kundera.cache.ehcache.EhCacheProvider"/>
<property name="kundera.cache.config.resource" value="/ehcache-test.xml"/>
</properties>
</persistence-unit>
SimpleComment domain class:
package bmsapp.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "SIMPLE_COMMENT", schema = "KunderaExamples#cassandra_pu")
#XmlRootElement(name = "SimpleComment")
public class SimpleComment {
#Id
#Column(name = "COMMENT_ID")
private int id;
#Column(name = "USER_NAME")
private String userName;
#Column(name = "COMMENT_TEXT")
private String commentText;
public SimpleComment() {
}
public SimpleComment(int commentId, String userName, String commentText) {
this.id = commentId;
this.userName = userName;
this.commentText = commentText;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCommentText() {
return commentText;
}
public void setCommentText(String commentText) {
this.commentText = commentText;
}
}
SpringExampleDao:
package bmsapp.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import bmsapp.domain.SimpleComment;
#Service
public class SpringExampleDao
{
#PersistenceContext(type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;
public SimpleComment addComment(int id, String userName, String commentText)
{
SimpleComment simpleComment = new SimpleComment(id, userName, commentText);
entityManager.persist(simpleComment);
return simpleComment;
}
public SimpleComment getCommentById(String Id)
{
SimpleComment simpleComment = entityManager.find(SimpleComment.class, Id);
return simpleComment;
}
public List<SimpleComment> getAllComments()
{
Query query = entityManager.createQuery("SELECT c from SimpleComment c");
List<SimpleComment> list = query.getResultList();
return list;
}
}
The relevant part of the stacktrace is:
nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
So you need to add a dependency to spring-orm, see http://mvnrepository.com/artifact/org.springframework/spring-orm.
However, I'm not sure that really solves your problem. In the description you're mentioning Neo4j and I cannot see what part of your description relates to that.

Having issues autowiring a sessionfactory bean with spring mvc and hibernate

I am trying to implement auto-wiring into my project, but it seems that my application isn't seeing my SessionFactory definition in my application-context.xml when I am running it.
I'm probably missing something really obvious, though I've tried several solutions from posts having similar issues with no success.
I am using Spring MVC and Hibernate.
Here is my application-context.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"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="arlua" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="serverDatasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>url</value>
</property>
<property name="username">
<value>${user}</value>
</property>
<property name="password">
<value>${pwd}</value>
</property>
</bean>
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>mapping/user_info.hbm.xml</value>
<value>mapping/login.hbm.xml</value>
<value>mapping/linked_accounts.hbm.xml</value>
<value>mapping/application_instance.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="dataSource" ref="serverDatasource"/>
</bean>
<bean id = "userInfoDaoImpl" class="arlua.dao.impl.UserInfoDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean id = "loginDaoImpl" class="arlua.dao.impl.LoginDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean id = "linkedAccountsDaoImpl" class="arlua.dao.impl.LinkedAccountsDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!--
<bean id = "applicationInstanceDaoImpl" class="arlua.dao.impl.ApplicationInstanceDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
-->
<!-- ************* TRANSACTION MANAGEMENT USING AOP **************** -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<aop:config>
<aop:pointcut id="allMethods" expression="execution(* arlua.dao.TableEntityFetchDao.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="myTransactionManager">
<tx:attributes>
<tx:method name="saveEntity"
propagation = "REQUIRES_NEW"
isolation = "READ_COMMITTED"
rollback-for = "Exception"/>
<tx:method name="updateEntity"
propagation = "REQUIRES_NEW"
isolation = "READ_COMMITTED"
rollback-for = "Exception"/>
<tx:method name="getEntity"
propagation = "REQUIRES_NEW"
isolation = "READ_COMMITTED"
rollback-for = "Exception"/>
<tx:method name="getAllEntities"
propagation = "REQUIRES_NEW"
isolation = "READ_COMMITTED"
rollback-for = "Exception"/>
</tx:attributes>
</tx:advice>
</beans>
Here is the controller class where I am trying to autowire.
package arlua.controller;
import arlua.dao.TableEntityFetchDao;
import arlua.dao.impl.ApplicationInstanceDaoImpl;
import arlua.service.SearchCriteria;
import arlua.service.UserAction;
import arlua.tables.ApplicationInstanceTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class SearchAppController{
#Autowired public ApplicationInstanceDaoImpl applicationInstanceDaoImpl;
private String input;
private ApplicationInstanceTable oldApp, newApp;
#RequestMapping(value = "/search_app_instance", method = RequestMethod.POST)
public String mySearchMethod(#ModelAttribute("search_criteria") SearchCriteria search){
input = search.getInput();
if(input != null)
input = input.toUpperCase();
return "redirect:search_app_instance";
}
#RequestMapping("/search_app_instance")
public ModelAndView mySuccessMethod(){
ModelAndView model = new ModelAndView("search_app_instance");
//Check and Make sure that the app exists
//ApplicationContext factory =
// new ClassPathXmlApplicationContext("spring-namespace.xml");
//TableEntityFetchDao urd = (TableEntityFetchDao)factory.getBean("applicationInstanceDaoImpl");
try{
ApplicationInstanceTable app =
(ApplicationInstanceTable) applicationInstanceDaoImpl.getEntity(input);
oldApp = app;
//Load app data into table
model.addObject("app_id", app.getApplication_id());
model.addObject("name", app.getName());
model.addObject("default_exp_period", app.getDefault_expiration_period());
model.addObject("server", app.getServer());
model.addObject("description", app.getDescription());
model.addObject("active", app.getActive());
model.addObject("conn_string", app.getConn_string());
model.addObject("creation_date", app.getCreation_date().getTime());
model.addObject("error", "");
}
catch(Exception e){
if(input != null)
{
model.addObject("error", "Application could not be found.");
input = "";
}
}
return model;
}
#RequestMapping(value = "/app_actions", method = RequestMethod.POST)
public String userActionsMethod(#ModelAttribute("user_action") UserAction action,
#ModelAttribute("app_info") ApplicationInstanceTable app_info){
if(action.getAction().equals("update_info"))
{
newApp = app_info;
return "redirect:update_app_info";
}
return "redirect:search_app_instance";
}
#RequestMapping("/update_app_info")
public ModelAndView updateInfoMethod(){
ModelAndView model = new ModelAndView("search_app_instance");
ApplicationContext factory =
new ClassPathXmlApplicationContext("spring-namespace.xml");
TableEntityFetchDao urd = (TableEntityFetchDao)factory.getBean("applicationInstanceDaoImpl");
newApp.setApplication_id(oldApp.getApplication_id());
newApp.setCreation_date(oldApp.getCreation_date());
urd.updateEntity(newApp);
model.addObject("msg", "Application '" + newApp.getApplication_id() + "' modified successfully.");
return model;
}
}
ApplicationInstanceDaoImpl Class
package arlua.dao.impl;
import arlua.dao.TableEntityFetchDao;
import arlua.tables.ApplicationInstanceTable;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
#Repository("applicationInstanceDaoImpl")
public class ApplicationInstanceDaoImpl extends TableEntityFetchDao{
public SessionFactory mySessionFactory;
#Resource(name = "mySessionFactory")
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;
}
public void saveEntity(Object applicationInstance) {
this.mySessionFactory.getCurrentSession().save((ApplicationInstanceTable)applicationInstance);
}
public ApplicationInstanceTable getEntity(Object application_id) {
return (ApplicationInstanceTable)this.mySessionFactory.getCurrentSession().
get(ApplicationInstanceTable.class, (String)application_id);
}
public void updateEntity(Object applicationInstance) {
this.mySessionFactory.getCurrentSession().update((ApplicationInstanceTable)applicationInstance);
}
public void deleteEntity(Object applicationInstance) {
this.mySessionFactory.getCurrentSession().delete((ApplicationInstanceTable)applicationInstance);
}
public List<?> getAllEntities() {
return this.mySessionFactory.getCurrentSession().createQuery
("FROM application_instance").list();
}
}
TableEntityFetchDao class
package arlua.dao;
import java.util.List;
import org.hibernate.SessionFactory;
/*
This class will serve as a generic blueprint for all of the other data access implementation classes
that are used to perform basic CRUD operations on the arlua tables (ie UserInfoDaoImpl).
*/
public abstract class TableEntityFetchDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
public abstract void saveEntity(final Object entity);
public abstract Object getEntity(final Object key);
public abstract void updateEntity(final Object entity);
public abstract void deleteEntity(final Object entity);
public abstract List<?> getAllEntities();
}
Here is most of my stack trace.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchAppController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchAppController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075)
at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:383)
at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:362)
at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82)
at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58)
at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119)
at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72)
at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)
at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:106)
at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 26 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public arlua.dao.impl.ApplicationInstanceDaoImpl arlua.controller.SearchAppController.applicationInstanceDaoImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
... 46 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationInstanceDaoImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:300)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 48 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mySessionFactory' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1083)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:541)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:156)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:297)
... 59 more
Edit: I ended up fixing my problem by autowiring into the interface TableEntityFetchDao rather than the class that was implementing it, ApplicationInstanceDaoImpl.
So, this
#Autowired public ApplicationInstanceDaoImpl applicationInstanceDaoImpl;
Became this
#Autowired public TableEntityFetchDao applicationInstanceDao;
And that seemed to fix my problem.
Instead of:
#Resource(name = "mySessionFactory")
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;
}
Use:
#Autowired
private SessionFactory mySessionFactory;
EDIT
As of the bellow comment:
Not sure why method is not working but my guess is that the parent TableEntityFetchDao class has the setter of session factory, then ApplicationInstanceDaoImpl - child class overrides it and spring for some reason does not like it, if TableEntityFetchDao would be an interface, setter would be injected, as #Resource serves the same purpose as #Autowired difference is that #Resource allows to specify the name of the bean which is injected, and #Autowire allows you mark the bean as not required.
To get #Resource working I would try to remove setter method from the parent class. Either way it makes no sense of having it there as it is not used. Also sessionFactory field. This can be removed as well. Then class contains only abstract methods and can be made an interface. Also I would annotate TableEntityFetchDao with #Service annotation for better understanding that it is a service-layer class.
#Resource(name = "mySessionFactory")
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;
}
try as #Autowired
public void setMySessionFactory(SessionFactory mySessionFactory){
this.mySessionFactory = mySessionFactory;
}
modify your code from the below code snippet in your spring configuration file
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingLocations">
<list>
<value>mapping/user_info.hbm.xml</value>
<value>mapping/login.hbm.xml</value>
<value>mapping/linked_accounts.hbm.xml</value>
<value>mapping/application_instance.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="dataSource" ref="serverDatasource"/>
I hope this code will work for you, and let me know , if still you are facing the problem

Autowired Fails with Spring Junit Test

Writing Junit Tests for my spring application. Because I am new at this I tried starting off by writing a Unit Test for a DAO class that I know works (ran it in JBoss). However, I cannot get it to work as a Unit Test in Eclipse. I keep getting an "Error creating bean... Could not autowire field: NoSuchBeanDefinition".
I saw errors similar to this on StackOverflow and other sites and it always ended up being a syntax error or attempting to autowire the Implementation of the interface as opposed to the Interface, etc. I don't see any of those errors with my code.
I did download Spring-test.jar separately from the Spring configuration that came with the project. Both are from Spring 2.5 however, so I don't think that should be an issue :/
Eclipse comes bundled with JUnit 4.8 and Spring Unit Test doesn't work with that so I downgraded my JUnit to use 4.4
One thing to consider... if you look at the code for my Unit Test you will notice that I autowire two fields: a SimpleJdbcTemplate at the Query Service I want to test. Well if I remove the DrugDao and all references to it, then the SimpleJdbcQuery auto-wires just fine.
Here is the stacktrace for your review:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tst.hcps.glucosemanagement.dataaccess.DrugDaoTest': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.hcps.glucosemanagement.repository.meds.DrugDao tst.hcps.glucosemanagement.dataaccess.DrugDaoTest.dQuery; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:127)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:85)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:95)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:139)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
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: com.hcps.glucosemanagement.repository.meds.DrugDao tst.hcps.glucosemanagement.dataaccess.DrugDaoTest.dQuery; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:435)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:240)
... 18 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:613)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:412)
... 20 more
Here is the Interface and Implementation:
DrugDao.java
package com.hcps.glucosemanagement.repository.meds;
import java.util.List;
import com.hcps.glucosemanagement.domain.meds.Drug;
public interface DrugDao {
public List<Drug> searchDrugsByPrimaryName(String facilityId, String name);
public List<Drug> searchDrugs(String facilityId, String primaryName, String secondaryName);
}
SpringJdbcDrugQuery.java
package com.hcps.glucosemanagement.repository.meds;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Service;
import com.hcps.glucosemanagement.domain.meds.Drug;
import com.hcps.glucosemanagement.repository.DaoOperations;
#Service
public class SpringJdbcDrugQuery extends DaoOperations implements DrugDao {
private static final Logger logger = Logger.getLogger(SpringJdbcDrugQuery.class);
public List<Drug> searchDrugsByPrimaryName(String facilityId, String name)
{
return searchDrugs(facilityId, name, null);
}
public List<Drug> searchDrugs(String facilityId, String primaryName, String secondaryName)
{
List<Drug> results = null;
StringBuffer sql = new StringBuffer();
HashMap<String, Object> namedParameters = new HashMap<String, Object>();
if(primaryName==null) return null;
sql = new StringBuffer();
sql.append("SELECT");
...
results = simpleJdbcTemplate.query(sql.toString(), new DrugMapper(),
return results;
}
private static final class DrugMapper implements ParameterizedRowMapper<Drug>
{
public Drug mapRow(ResultSet rs, int rowNum) throws SQLException {
Drug drug = new Drug();
drug.setFacilityId(rs.getString("FACILITY_ID"));
drug.setPrimaryName(rs.getString("PRIMARY_NAME"));
drug.setSecondaryName(rs.getString("SEC_NAME"));
return drug;
}
}
}
DrugDaoTest2.java (located in a separate source folder at first, then tried it in the same folder)
package com.hcps.glucosemanagement.repository.meds;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.hcps.glucosemanagement.domain.meds.Drug;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={
"classpath:common-test.xml"
})
public class DrugDaoTest2 {
#Autowired
DrugDao dQuery;
#Autowired
SimpleJdbcTemplate queryTemplate;
#Test public void glucoseFetch() {
List<Drug> rslts = dQuery.searchDrugsByPrimaryName(null, "INSU*");
assertTrue(rslts.size()>0);
int i=0;
System.out.println(i);
}
public void setDrugDao(DrugDao drugDao) {
this.dQuery = drugDao;
}
}
common-test.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
>
<!--
Test configuration for Spring/JUnit Testing
-->
<bean id="contextApplicationContextProvider" class="com.hcps.glucosemanagement.spring.ApplicationContextProvider" />
<bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="beans">
<map>
<entry key="bean:name=Log4jJmxServiceMBean" value-ref="glucosemanagement.Log4jJmxService" />
</map>
</property>
</bean>
<bean id="glucosemanagement.Log4jJmxService" class="com.hcps.glucosemanagement.logging.Log4jJmxService" />
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="parameterMappingInterceptor" class="org.springframework.web.portlet.handler.ParameterMappingInterceptor" />
<bean id="viewResolverCommon" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="2"
p:cache="false"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"
/>
<bean id="defaultExceptionHandler" class="org.springframework.web.portlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="../error"/>
<property name="exceptionMappings">
<props>
<prop key="javax.portlet.PortletSecurityException">notAuthorized</prop>
<prop key="javax.portlet.UnavailableException">notAvailable</prop>
</props>
</property>
</bean>
<bean id="simpleParameterJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="hciDataSource" />
</bean>
<bean id="hciDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#//vir-tst.com:1521/qar01.world" />
<property name="username" value="ccuser" />
<property name="password" value="bueno" />
<property name="maxActive" value="30" />
<property name="maxWait" value="30" />
<property name="maxIdle" value="30" />
</bean>
</beans>
My mistake: there was another Spring Configuration file referenced elsewhere that I missed. Adding this field and defining setters in my Unit Test for any autowired fields solved the problem.
I am using this checklist now when these types of errors occur:
Make sure that implementing class of Interface type uses “#Service”
annotation
Make sure beans are configured properly in the XML:
Simplest way is to use:
<context:component-scan base-package="com.customization.packagename" />
This adds all classes under the package name
Or create XML Bean Definitions
I had the similar issue and found that while I could AutoWire classes successfully in Eclipse, surefire required only interfaces to be AutoWired. Especially this occurs only when using Cobertura for instrumenting, so pretty sure there is something wrong with the proxy generation. For now, I have just introduced a new interface as it was appropriate for my use-case but there should definitely be another appropriate solution.
Add a bean definition of type SpringJdbcDrugQuery to common-test.xml
I encounter this problem too, and I just add setter, then it works well.

Resources