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.
Related
I want to reference a java config class in my Spring config xml file, but failed, please see below my code:
Bean1 class :
package c2_5_2.ref.javaconfig.from.xml;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component("bean1")
public class Bean1 {
#Autowired
public Bean1(Bean2 bean2)
{
this.bean2 = bean2;
}
private Bean2 bean2;
public Bean2 getBean2() {
return bean2;
}
}
Bean2 class :
package c2_5_2.ref.javaconfig.from.xml;
import java.util.List;
public class Bean2 {
private List<String> nameList;
public List<String> getNameList() {
return nameList;
}
public void setNameList(List<String> nameList) {
this.nameList = nameList;
}
public void displayNames()
{
for(String name : nameList)
{
System.out.println(name);
}
}
}
Bean3 Class :
package c2_5_2.ref.javaconfig.from.xml;
public class Bean3 {
private Bean1 b1;
public Bean1 getB1() {
return b1;
}
public void setB1(Bean1 b1) {
this.b1 = b1;
}
public void introduce()
{
System.out.println("this is bean 3");
}
}
Java Config Class :
package c2_5_2.ref.javaconfig.from.xml;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages= {"c2_5_2.ref.javaconfig.from.xml"})
public class BeanConfig {
#Bean(name="bean2")
public Bean2 getBean2()
{
Bean2 b2 = new Bean2();
List<String> nameList = new ArrayList<String>();
nameList.add("Bitt");
nameList.add("Rock");
nameList.add("Lucas");
nameList.add("Crius");
b2.setNameList(nameList);
return b2;
}
}
BeanConfig.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="c2_5_2.ref.javaconfig.from.xml.BeanConfig"></bean>
<bean id="bean3" class="c2_5_2.ref.javaconfig.from.xml.Bean3"></bean>
</beans>
Run Test method :
private static void test3()
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("c2_5_2/ref/javaconfig/from/xml/BeanConfig.xml");
Bean3 b3 = ctx.getBean(Bean3.class);
b3.introduce();
Bean1 b1 = ctx.getBean(Bean1.class);
}
Get following output and error message:
Oct 13, 2017 9:55:16 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#6d9c638: startup date [Fri Oct 13 09:55:16 CST 2017]; root of context hierarchy
Oct 13, 2017 9:55:16 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [c2_5_2/ref/javaconfig/from/xml/BeanConfig.xml]
**this is bean 3**
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'c2_5_2.ref.javaconfig.from.xml.Bean1' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:348)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:335)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1101)
at c2_5_2.ref.javaconfig.from.xml.Test_Driven.test3(Test_Driven.java:33)
at c2_5_2.ref.javaconfig.from.xml.Test_Driven.main(Test_Driven.java:12)
So from the output we can see the spring configuration xml file is found by spring framework because we got output "This is bean 3", but other 2 beans, "bean1" and "bean2" cannot be found even though I put the qualified name of BeanConfig class as a value to class property of the bean element in BeanConfig.xml file.
My concern is why spring cannot find the Bean definition, how to fix it?
if you use xml as config file to load the context you need to add <context:component-scan base-package="c2_5_2.ref.javaconfig.from.xml" /> which will fix your problem. since you code just create the BeanConfig class as a bean but it doesn't know that it is a configuration and trigger the scan the package. because you just create a bean.
once you add context-scan-package in ur xml, it will scan and get the BeanConfig file as config class which will create the bean2 and scan the package (redundant package)
Via component scanning
#Configuration is meta-annotated with #Component, therefore
#Configuration classes are candidates for component scanning
(typically using Spring XML's element) and
therefore may also take advantage of #Autowired/#Inject like any
regular #Component. In particular, if a single constructor is present
autowiring semantics will be applied transparently:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="c2_5_2.ref.javaconfig.from.xml.BeanConfig"></bean>
<bean id="bean3" class="c2_5_2.ref.javaconfig.from.xml.Bean3"></bean>
<context:component-scan base-package="c2_5_2.ref.javaconfig.from.xml" />
</beans>
update: if you want to create the bean as configuration file you can do:
Via Spring XML
<beans>
<context:annotation-config/>
<bean class="c2_5_2.ref.javaconfig.from.xml.BeanConfig"/>
</beans>
see detail : how spring look for #Configuration
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);
}
}
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.
I have downloaded tutorial zip fom here. It contains Application class with main-method
package hello;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Greeting class
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
and GreetingController
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
This works nice, but I want to create some Greeting object with using Spring beans (with using applicationContext.xml), so I create src/main/resources directory (I am using maven to configure this tutorial) and put there applicationContext.xml which looks like
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name = "greeting" class="hello.Greeting">
<constructor-arg index="0" value = "25" />
<constructor-arg index="1" value = "Hello!" />
</bean>
</beans>
After that I add
#Autowired
Greeting gr;
to Greeting controller and get
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: hello.Greeting hello.GreetingController.gr; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [hello.Greeting] 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: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 hello.Application.main(Application.java:12)
How can I make this construction work?
Thanks.
Add the #Qualifier annotation also:
#Autowired
#Qualifier("greeting")
Greeting gr;
The exception simply means that it was not able to create the bean GreetingController because of the dependency to your Greeting class (when you added it and annotated with #Autowire).
It could be that your applicationContext.xml can't be located.
Make sure you define these on your web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/location/of/your/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Hope this helps.
expected at least 1 bean which qualifies as autowire candidate for this dependency.
means that Spring didn't create any bean of Greeting class, so i guess that spring didn't import you file.
Official documentaion advises to use #ImportResource.
So it would be somthing like:
#ComponentScan
#ImportResource("classpath:/applicationContext.xml")
#EnableAutoConfiguration
public class Application {
...
}
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);
}