DAO Testing - Spring + JPA Autowiring issue - java

I'm trying to use Spring on top of JPA with a Hibernate implementation. I'd like to use Spring for at least Annotation, Autowiring & Transaction management. I keep running into the below issue though. Any help would be greatly appreciated!
My GenericDAO Implementation:
package gov.cms.cicdim.cpc.data.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
public abstract class GenericDAO<K, T extends Serializable>
implements IGenericDAO<K, T>
{
protected Class<T> entityClass;
#PersistenceContext
protected EntityManager entityManager;
#Autowired
public GenericDAO()
{
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[1];
}
public T findOne(K id)
{
if(isEmpty(id)) { return null; }
return this.entityManager.find(entityClass, id);
}
public List<T> findAll()
{
return this.entityManager.createQuery("from " + entityClass.getName()).getResultList();
}
public void create(T entity)
{
this.entityManager.persist(entity);
this.entityManager.close();
}
public void update(T entity)
{
this.entityManager.merge(entity);
this.entityManager.flush();
this.entityManager.close();
}
public void delete(T entity)
{
this.entityManager.remove(entity);
this.entityManager.close();
}
public void deleteById(K id)
{
T entity = findOne(id);
delete(entity);
}
/**
* Utility method to determine if objects is empty or all elements are null for optimization purposes.
*
* #param objects the objects
* #return true, if is empty
*/
protected boolean isEmpty(Object...objects) {
if(objects.length == 0) {
return true;
}
for(Object o : objects) {
if(o != null) {
return false;
}
}
return true;
}
}
The DAO itself:
package gov.cms.cicdim.cpc.data.dao;
import gov.cms.cicdim.cpc.data.model.Practice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* The Class PracticeDAO for CRUD operations for Practice data.
*/
#Repository
#Transactional
public class PracticeDAO extends GenericDAO<String, Practice>
implements IPracticeDAO
{
public PracticeDAO(){}
/** The Constant logger. */
private static final Log logger = LogFactory.getLog(PracticeDAO.class);
#Override
public Practice findPersonByFullName(String full_Name) {
// TODO Auto-generated method stub
return null;
}
}
The test DAO: Not all tests included for space (In src/test/java)
package gov.cms.cicdim.cpc.data.dao;
import gov.cms.cicdim.cpc.data.model.Practice;
import java.util.List;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
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 org.springframework.transaction.annotation.Transactional;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/applicationContext.xml")
#Transactional
public class PracticeDAOTest extends TestCase
{
#Autowired
public PracticeDAO testPracticeDAO;
public void setPracticeDAO(PracticeDAO testPracticeDAO) {
this.testPracticeDAO = testPracticeDAO;
}
boolean doit = true;
#Test
public void testCreatePracticeDAO(){
if(doit){
Practice practice = generatePractice();
String porg = practice.getParentOrgName();
String pid = practice.getPracticeId();
//create
try {
testPracticeDAO.create(practice);
String pratice_id = testPracticeDAO.findOne(pid).getPracticeId();
assertEquals("Practice id check", pid, pratice_id);
} catch (Exception e) {
e.printStackTrace();
throw new AssertionFailedError("Practice Save failed");
}
// test update
try{
practice.setSiteName("baltimore");
if(testPracticeDAO.findOne(pid) !=null){
testPracticeDAO.update(practice);
String site_Name = testPracticeDAO.findOne(pid).getSiteName();
assertEquals("Practice Site check", "baltimore", site_Name);
}
} catch(Exception e){
e.printStackTrace();
throw new AssertionFailedError("Practice update failed!");
}
}
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="ApplicationEntityManager">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="javax.persistence.jdbc.url"
value="xxxxxxxxx"/>
<property name="javax.persistence.jdbc.user" value="xxxxxxx"/>
<property name="javax.persistence.jdbc.password" value="xxxxxxx"/>
</properties>
</persistence-unit>
</persistence>
applicationContext.xml (In src/main/resources)
<?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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config/>
<tx:annotation-driven />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="persistenceUnitName" value="ApplicationEntityManager" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="xxxxxxx" />
<property name="username" value="xxxxxxx" />
<property name="password" value="xxxxxxx" />
</bean>
<context:component-scan base-package="gov.cms.cicdim.cpc.data.dao"/>
<!-- Add new DAOs here -->
<bean id="practiceDAO" class="gov.cms.cicdim.cpc.data.dao.PracticeDAO"/>
<bean id="testPracticeDAO" class="gov.cms.cicdim.cpc.data.dao.PracticeDAO"/>
<!-- Add new Managers here -->
</beans>
And the STACKTRACE:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gov.cms.cicdim.cpc.data.dao.PracticeDAOTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public gov.cms.cicdim.cpc.data.dao.PracticeDAO gov.cms.cicdim.cpc.data.dao.PracticeDAOTest.testPracticeDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
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:321)
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:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
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.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:174)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public gov.cms.cicdim.cpc.data.dao.PracticeDAO gov.cms.cicdim.cpc.data.dao.PracticeDAOTest.testPracticeDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 32 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 34 more
Results :
Tests in error:
testCreatePracticeDAO(gov.cms.cicdim.cpc.data.dao.PracticeDAOTest): Error creating bean with name 'gov.cms.cicdim.cpc.data.dao.PracticeDAOTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public gov.cms.cicdim.cpc.data.dao.PracticeDAO gov.cms.cicdim.cpc.data.dao.PracticeDAOTest.testPracticeDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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)}
testFindAllPractices(gov.cms.cicdim.cpc.data.dao.PracticeDAOTest): Error creating bean with name 'gov.cms.cicdim.cpc.data.dao.PracticeDAOTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public gov.cms.cicdim.cpc.data.dao.PracticeDAO gov.cms.cicdim.cpc.data.dao.PracticeDAOTest.testPracticeDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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)}

Spring declarative transactions are implemented using proxies. By default if the proxied class implements an interface, it uses JDK Dynamic proxy, which is what is being used here, as PracticeDAO implements IPracticeDAO.
The proxy created by spring implements the same interface IPracticeDAO, and a bean of that proxy is registered. And since you're autowiring on PracticeDAO, the proxy bean could not be autowired, as instances of sibling classes are not compatible. That is why you should almost always use #Autowired annotation on interface type, rather than implementing class type.
In your case, try autowiring on IPracticeDAO instead of PracticeDAO, and it will work fine.

Related

Injection of autowired dependencies failed with Spring MVC

I'm trying to make a simple application with SPing but I keep getting this error and I dont understand why.
I have tried everything, even wre-wrote the whole app. Dont even know what the problem could be.
This is the error I get:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blogPostController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.vst.blog.service.BlogService com.vst.blog.controller.BlogPostController.blogServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
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:4689)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5155)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.vst.blog.service.BlogService com.vst.blog.controller.BlogPostController.blogServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] 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:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] 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:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 24 more
Jul 14, 2020 9:46:20 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blogPostController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.vst.blog.service.BlogService com.vst.blog.controller.BlogPostController.blogServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
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:4689)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5155)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.vst.blog.service.BlogService com.vst.blog.controller.BlogPostController.blogServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] 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:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] 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:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 24 more
Jul 14, 2020 9:46:20 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blogPostController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.vst.blog.service.BlogService com.vst.blog.controller.BlogPostController.blogServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
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:4689)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5155)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.vst.blog.service.BlogService com.vst.blog.controller.BlogPostController.blogServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] 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:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.vst.blog.service.BlogService] 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:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 24 more
Here is the class that's giving issues(BlogPostController)
package com.vst.blog.controller;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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.servlet.ModelAndView;
import com.vst.blog.model.BlogPost;
import com.vst.blog.service.BlogService;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
#Controller
public class BlogPostControllerImpl {
private static final Logger logger = Logger
.getLogger(BlogPostControllerImpl.class);
#Autowired
BlogService blogServiceImpl;
BlogPostControllerImpl(){}
#RequestMapping(value= "/", method = RequestMethod.GET)
public ModelAndView index() {
return new ModelAndView("redirect:/web-inf/pages/index.jsp");
}
#RequestMapping(value = "/loadPosts")
public ModelAndView listPosts(ModelAndView model) throws IOException {
List<BlogPost> listPosts = blogServiceImpl.selectBlogPostS();
model.addObject("listPosts", listPosts);
model.setViewName("post");
return model;
}
#RequestMapping(value = "/newPost", method = RequestMethod.GET)
public ModelAndView newPost(ModelAndView model) {
BlogPost post = new BlogPost();
model.addObject("post", post);
model.setViewName("post_form");
return model;
}
#RequestMapping(value = "/savePost", method = RequestMethod.POST)
public ModelAndView savePost(#ModelAttribute BlogPost post) throws SQLException {
if (post.getBlog_id() == 0) {
blogServiceImpl.insertBlogPost(post);
} else {
blogServiceImpl.updateBlogPost(post);
}
return new ModelAndView("redirect:/loadAlbums");
}
#RequestMapping(value = "/editPost", method = RequestMethod.GET)
public ModelAndView editPost(HttpServletRequest request) {
int postId = Integer.parseInt(request.getParameter("blog_id"));
BlogPost post = blogServiceImpl.selectBlogPostById(postId);
ModelAndView model = new ModelAndView("post_form");
model.addObject("post", post);
return model;
}
#RequestMapping(value = "/deletePost", method = RequestMethod.GET)
public ModelAndView deletePost(HttpServletRequest request) throws SQLException {
int postId = Integer.parseInt(request.getParameter("blog_id"));
blogServiceImpl.deleteBlogPost(postId);
return new ModelAndView("redirect:/loadPosts");
}
}
This is the class interface.
package com.vst.blog.service;
import java.sql.SQLException;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.vst.blog.model.BlogPost;
public interface BlogService {
public void insertBlogPost(BlogPost post) throws SQLException;
public BlogPost selectBlogPostById(int id);
public List<BlogPost> selectBlogPostS();
public void deleteBlogPost(int id) throws SQLException;
public void updateBlogPost(BlogPost post) throws SQLException;
}
And here is the implementation of it:
package com.vst.blog.service;
import java.sql.SQLException;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.vst.blog.dao.BlogPostDao;
import com.vst.blog.dao.BlogPostDaoImpl;
import com.vst.blog.dao.BlogPostDaoImpl;
import com.vst.blog.model.BlogPost;
#Service
#Transactional
public class BlogServiceImpl implements BlogService {
#Autowired
private BlogPostDao postDao;
public BlogServiceImpl () {
//postDao = new BlogPostDaoImpl();
}
public void insertBlogPost(BlogPost post) throws SQLException {
postDao.insertBlogPost(post);
}
public BlogPost selectBlogPostById(int id) {
return postDao.selectBlogPostById(id);
}
public List<BlogPost> selectBlogPostS() {
return postDao.selectBlogPostS();
}
public void deleteBlogPost(int id) throws SQLException {
postDao.deleteBlogPost(id);
}
public void updateBlogPost(BlogPost post) throws SQLException{
postDao.updateBlogPost(post);
}
}
This is DaoImpl
package com.vst.blog.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.vst.blog.model.BlogPost;
#Service
#Transactional
public class BlogPostDaoImpl implements BlogPostDao {
public BlogPostDaoImpl () {}
#Autowired
private SessionFactory sessionFactory;
public void insertBlogPost(BlogPost post) {
sessionFactory.getCurrentSession().saveOrUpdate(post);
}
public BlogPost selectBlogPostById(int id) {
return (BlogPost) sessionFactory.getCurrentSession().get(
BlogPost.class, id);
}
#SuppressWarnings("unchecked")
public List<BlogPost> selectBlogPostS() {
return sessionFactory.getCurrentSession().createQuery("from blog")
.list();
}
public void deleteBlogPost(int id) {
BlogPost post = (BlogPost) sessionFactory.getCurrentSession().load(
BlogPost.class, id);
if (null != post) {
this.sessionFactory.getCurrentSession().delete(post);
}
}
public BlogPost updateBlogPost(BlogPost post) {
sessionFactory.getCurrentSession().update(post);
return post;
}
}
And here is its interface
package com.vst.blog.dao;
import java.sql.SQLException;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.vst.blog.model.*;
#Repository
public interface BlogPostDao {
public void insertBlogPost(BlogPost post) throws SQLException;
public BlogPost selectBlogPostById(int id);
public List<BlogPost> selectBlogPostS();
public void deleteBlogPost(int id) throws SQLException;
public BlogPost updateBlogPost(BlogPost post) throws SQLException;
}
This is spring-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">
<!-- Specifying base package of the Components like Controller, Service,
DAO -->
<context:component-scan base-package="com.vst" />
<!-- Getting Database properties -->
<context:property-placeholder location="classpath:application.properties" />
<mvc:annotation-driven />
<!-- Specifying the Resource location to load JS, CSS, Images etc -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- View Resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- DataSource -->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
id="dataSource">
<property name="driverClassName" value="${database.driver}"></property>
<property name="url" value="${database.url}"></property>
<property name="username" value="${database.user}"></property>
<property name="password" value="${database.password}"></property>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<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="com.vst.blog.model"></property>
</bean>
<!-- Transaction -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Here some tips to detect this rare errors related to:
Injection of autowired dependencies failed
Use just one scan:
<context:component-scan base-package="com.VST" />
Instead
<context:component-scan base-package="com.VST.blog.service" />
<context:component-scan base-package="com.VST.blog.controller" />
<context:component-scan base-package="com.VST.blog.dao" />
validate that all your spring beans are in this package or child of it:
com.VST
create an empty class with some method inside of your base package com.vst and try to autowire it. This could reveal that not even a simple empty autowire works!!
Remove "impl" from autowired clases. In your example, change this
BlogService blogServiceImpl;
to
BlogService blogService;
in your BlogPostControllerImpl
Another tips
don't use uppercase in packages
use spring boot :D

Getting NoSuchBeanDefinitionException even after using all annotations and component scan

I am getting
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'springTest': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.learn.stackoverflow.general.Person
com.learn.stackoverflow.general.SpringTest.person; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.learn.stackoverflow.general.Person] 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)}
even after using all the annotations, I have annotated all my classes with #Component and adding component scan but still #Autowired gives me error.
Below are my classes:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
#Component
public class SpringTest {
#Autowired
Person person;
public static void main(String[] args) {
testApplicationContext();
}
private static void testApplicationContext() {
// here static and instance initializers of Person class will be invoked right away, even when we are not calling getBean method
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("C:\\E_Drive\\Projects\\Workspace\\Test\\CS101\\src\\com\\learn\\stackoverflow\\general\\bean.xml");
SpringTest springTest = (SpringTest) applicationContext.getBean("springTest");
}
}
Person class:
import org.springframework.context.annotation.Scope;
import com.bea.core.repackaged.springframework.stereotype.Component;
#Component
#Scope(value="singleton")
public class Person {
static{
System.out.println("1");
}
{
System.out.println("2");
}
}
XML file:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
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">
<context:component-scan base-package="com.learn.stackoverflow.general"/>
<!-- <bean id = "person" class = "com.learn.stackoverflow.general.Person" scope="singleton">
</bean> -->
<bean id = "springTest" class = "com.learn.stackoverflow.general.SpringTest" scope="singleton">
</bean>
</beans>
Use the right import in the Person.class. Instead of
import com.bea.core.repackaged.springframework.stereotype.Component;
you have to use
import org.springframework.stereotype.Component;
BTW you can avoid using
#Scope(value="singleton")
since singleton is a default scope for Spring beans.

#Autowired fields causes org.springframework.beans.factory.BeanCreationException

When i try to use #Autowired it gives me exceptions
Things I have added to use #Autowired annotation
context:annotation-config /
bean id = "GoAnalyserService" class ="com.dataanalyser.serviceimpl.GoAnalyserServiceImpl"/
context:component-scan base-package="com.dataanalyser.service"/
My spring-dispatcher-servlet
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<context:component-scan base-package="com.dataanalyser.controller"/>
<!-- <context:component-scan base-package="com.dataanalyser"/> -->
<context:component-scan base-package="com.dataanalyser.dao"/>
<context:component-scan base-package="com.dataanalyser.service"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:annotation-config />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value="/WEB-INF/" />
<property name = "suffix" value = ".html" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/GoAnalyserDB" />
<property name="username" value="postgres" />
<property name="password" value="toor" />
</bean>
<bean id = "goAnalyserService" class = "com.dataanalyser.serviceimpl.GoAnalyserServiceImpl"/>
<bean id = "userDao" class = "com.dataanalyser.daoimpl.UserDaoImpl"/>
</beans>
My controller class
#Controller
public class GoAnalyserControl {
public GoAnalyserControl()
{
System.out.println("------- Inside the controller -------");
}
#Autowired
GoAnalyserService goAnalyserService;
#RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"})
public #ResponseBody String logInCheckerFn(#RequestBody UserLogData userLogData){
System.out.println("inside loginChecker()");
//GoAnalyserService goAnalyserService = new GoAnalyserServiceImpl();
Integer userAuthFlag = goAnalyserService.checkUserAuth(userLogData);
System.out.println(userAuthFlag.toString());
return userAuthFlag.toString();
}
}
My Service class
public interface GoAnalyserService {
public Integer checkUserAuth(UserLogData userLogData);
}
My Service implementation class
public class GoAnalyserServiceImpl implements GoAnalyserService {
#Autowired
UserDao userDao;
#Override
public Integer checkUserAuth(UserLogData userLogData){
//UserDao userDao = new UserDaoImpl();
if((userDao.getUserCount(userLogData.getUserName())) == 1){
String dbPass = userDao.getUserPass(userLogData.getUserName());
if( dbPass.equals(userLogData.getPassword()))
return 1;
else
return 2;
}else
return 0;
}
}
When i try it out without #Autowired annotation, this code works out fine, but when i add #Autowired it gives me
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'goAnalyserControl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.dataanalyser.service.GoAnalyserService com.dataanalyser.controller.GoAnalyserControl.goAnalyserService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.dataanalyser.serviceimpl.GoAnalyserService] for bean with name 'GoAnalyserService' defined in ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.dataanalyser.serviceimpl.GoAnalyserService
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.dataanalyser.service.GoAnalyserService com.dataanalyser.controller.GoAnalyserControl.goAnalyserService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.dataanalyser.serviceimpl.GoAnalyserService] for bean with name 'GoAnalyserService' defined in ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.dataanalyser.serviceimpl.GoAnalyserService
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.dataanalyser.serviceimpl.GoAnalyserService] for bean with name 'GoAnalyserService' defined in ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.dataanalyser.serviceimpl.GoAnalyserService
and few more like this,
I think something is wrong in spring-dispatcher-servlet.xml, I have searched a lot, still cant find the thing wrong. I there any jar file that need to be added to the project ....??
Put #Repo on GoAnalyserServiceImpl class
May be resolve your error beacuse when you used #Autowired you dont wory about creating object.And use #Autowired must be at top of class #Controller or #Repo or #Service / only #Component. annotation is used to mark the class as the controller in Spring 3.
Try to remove
<bean id = "goAnalyserService" class = "com.dataanalyser.serviceimpl.GoAnalyserServiceImpl"/>
from xml configuration.
And annotate GoAnalyserServiceImpl as #Component.
First of all, make sure that the class you are declaring in your XML exists inside the package. Then, annotate your class with #Component annotation. Spring uses these annotations to find the class it is supposed to instantiate when #Autowired is used.
Your component-scan declaration is:
<context:component-scan base-package="com.dataanalyser.service"/>
while your exception message states that :
Cannot find class com.dataanalyser.serviceimpl.GoAnalyserService
So you have a wrong package declaration in your component scan. Make it :
<context:component-scan base-package="com.dataanalyser.serviceimpl"/>
or change the package of the class to com.dataanalyser.service
Assuming of course that your service class is annotated properly

Using #autowire annotation in spring boot is throwing 'BeanCreationException'

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daaSController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.ca.mock.dass.storage.mockservice.StorageService com.ca.mock.daas.storage.controller.DaaSController.storageService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ca.mock.dass.storage.mockservice.StorageService] 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), #org.springframework.beans.factory.annotation.Qualifier(value=storageService)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
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:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at com.ca.mock.daas.storage.controller.Application.main(Application.java:15)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.ca.mock.dass.storage.mockservice.StorageService com.ca.mock.daas.storage.controller.DaaSController.storageService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ca.mock.dass.storage.mockservice.StorageService] 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), #org.springframework.beans.factory.annotation.Qualifier(value=storageService)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:522)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298)
... 16 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ca.mock.dass.storage.mockservice.StorageService] 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), #org.springframework.beans.factory.annotation.Qualifier(value=storageService)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1118)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:967)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:494)
... 18 common frames omitted
Code related to this error:
Application.java
package com.ca.mock.daas.storage.controller;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ca.mock.dass.storage.mockservice.StorageServiceMockImpl;
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
DaaSController.java
package com.ca.mock.daas.storage.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ca.mock.dass.storage.mockservice.StorageService;
#RestController
public class DaaSController {
private static final String V1_DAAS = "/v1/daas";
private static final String APPLICATION_JSON_CHARSET_UTF_8 = "application/json; charset=utf-8";
#Autowired
#Qualifier("storageService")
StorageService storageService;
#RequestMapping(value = V1_DAAS, produces = APPLICATION_JSON_CHARSET_UTF_8)
public String cecs() {
return storageService.cecs();
}
}
StorageService.java
package com.ca.mock.dass.storage.mockservice;
public interface StorageService {
String cecs();
}
StorageServiceImpl.java
package com.ca.mock.dass.storage.mockservice;
public class StorageServiceMockImpl implements StorageService {
#Override
public String cecs() {
return DassStorageUtil.mockDasdWithMetrics("Cecs");
}
DassStorageUtil has code to read from a file and return a string.
application-context.xml
<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"
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:task="http://www.springframework.org/schema/task"
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
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.ca.mock.daas.storage.controller"/>
<context:annotation-config />
<bean id="daaSController" class="com.ca.mock.daas.storage.controller.DaaSController"/>
<bean id="storageService" class="com.ca.mock.dass.storage.mockservice.StorageServiceMockImpl"/>
</beans>
Can someone please help me with this error.
If you're intending to use the XML configuration, you need to import that resource
#ComponentScan
#EnableAutoConfiguration
#ImportResource("application-context.xml")
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}

Error creating bean with name 'countriesDao': Injection of autowired dependencies failed;

Im trying to start Tomcat but when I try start it im getting the following error
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'countriesDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.fexco.helloworld.web.util.CustomHibernateDaoSupport.anyMethodName(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
CountriesDao
package com.fexco.helloworld.web.dao;
import com.fexco.helloworld.web.model.Countries;
public interface CountriesDao {
void save(Countries countries);
void update(Countries countries);
void delete(Countries countries);
Countries findByCountry(String country);
}
The start of CountriesDaoImpl
package com.fexco.helloworld.web.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.fexco.helloworld.web.model.Countries;
import com.fexco.helloworld.web.util.CustomHibernateDaoSupport;
#Repository("countriesDao")
public class CountriesDaoImpl extends CustomHibernateDaoSupport implements CountriesDao{
public void save(Countries countries){
getHibernateTemplate().save(countries);
}
......
}
Some of Application-config.xml
<bean id="countriesDao" class="com.fexco.helloworld.web.dao.CountriesDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
....
<context:annotation-config />
<context:component-scan base-package="com.fexco.helloworld.web" />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
CustomHibernateDaoSupport class
package com.fexco.helloworld.web.util;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport
{
#Autowired
public void anyMethodName(SessionFactory sessionFactory)
{
setSessionFactory(sessionFactory);
}
}
Is the error because CountriesDaoImpl isnt really implementing CountriesDao?
Does anyone know how to solve this error?
Thanks
It seems you do not have session factory defined in your dao Implementation class. You should defined one if not already defined And avoid using both configurations It will messed up things i.e
#Autowired
#Qualifier("sessionFactory")
public void seSessionFactory(SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}

Categories