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 {
...
}
Related
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.
My tomcat is refusing to launch my application due to this error
Error creating bean with na
me 'Individual_Controller': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Cou
ld not autowire field: private net.service.datastore.Indiv
idual_Service net.controller.Individual_Controller.S
ervice; nested exception is org.springframework.beans.factory.NoSuchBeanDefiniti
onException: No qualifying bean of type
[net.service.datastore.Individual_Service] found for dependency: expected at least 1 bean which qu
alifies as autowire candidate for this dependency. Dependency annotations: {#org
.springframework.beans.factory.annotation.Autowired(required=true)}
expected at least 1 bean which qualifies a
s autowire candidate for this dependency. Dependency annotations: {#org.springfr
amework.beans.factory.annotation.Autowired(required=true)}
this is my service class
public long createT(Individual individual);
public Individual updateT(Individual individual);
public void deleteT(String tin);
public List<Individual> getAllTs();
public Individual getT(String t);
public List<Individual> getAllTs(String individual);
this is my controller class that is calling the service layer
#Autowired
private Individual_Service service;
#RequestMapping("searchT")
public ModelAndView searchT(#RequestParam("searchName") String searchName) {
logger.info("Searching the T: "+searchName);
List<Individual> tList = service.getAllTs(searchName);
return new ModelAndView("serviceDescription", "tList", tList);
}
this is the complete controller class
#Controller
public class IndividualController {
private static final Logger logger = Logger.getLogger(IndividualController.class);
public IndividualController() {
System.out.println("Individual_Controller()");
}
#Autowired
private IndividualService service;
#RequestMapping("searchT")
public ModelAndView searchT(#RequestParam("searchName") String searchName) {
logger.info("Searching the T: "+searchName);
List<Individual> tinList = service.getAllTs(searchName);
return new ModelAndView("serviceDescription", "tList", tList);
}
complete service interface class for the individual_service
package net.service.datastore;
import java.util.List;
import net.model.Individual;
public interface IndividualService {
public long createT(Individual individual);
public Individual updateT(Individual individual);
public void deleteT(String t);
public List<Individual> getAllTs();
public Individual getT(String t);
public List<Individual> getAllTs(String individual);
}
Please what could be wrong?
Looks like no bean of class Individual_Service is loaded in Application Context. There can be multiple reasons for that.
If you are using xml based configuration , please make sure that xml file is either included in web.xml using ContextLoaderListner.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-bean.xml
</param-value>
</context-param>
or in dispatcher-servlet.xml / applicationContext.xml
<import resource="classpath:bean.xml" />
If you are using annotation based Approach , make sure the class is properly annotated with #Component or #Bean or #Service or any other annotation based on application requirement.
Make sure path in context:component-scan is covering the package of Individual_Service.java
<context:component-scan base-package="net.service.datastore.*" />
Hope one of these point resolve your issue.
If not can you please provide your web.xml , dispatcher-servlet.xml or Spring configuration class and Individual_Service.java .
There's some information missing to provide a complete answer.
But basically, you should make sure of the following:
Your IndividualService implementation class should be annotated with #Service
Your IndividualController class should be annotated with #Controller
The field IndividualService in IndividualController should be annotated with #Autowired (or #Inject)
Both classes should be scanned in your Spring context config class (or file)
Here is how it should look like :
IndividualService.java :
package com.company.myapp.service;
//...imports...
#Service
public class IndividualService {
//.. fields/methods...
}
IndividualController.java :
package com.company.myapp.controller;
//...imports...
#Controller
public class IndividualController{
#Autowired
private IndividualService individualService;
//.. other fields/methods...
}
MyAppConfiguration.java :
package com.company.myapp;
//...imports...
#Configuration
#EnableWebMvc
//...other Spring config annotation...
#ComponentScan(basePackages = "com.company.myapp")
public class MyAppSpringConfiguration{
//...other configuration...
}
To know which class is your Spring config class, you should have a look at your webapp descriptor file (web.xml), and see which contextConfigLocation is provided as param to the Spring servlet (DispatcherServlet). If your're user servlet 3+ without web.xml, look for a class that implements WebApplicationInitializer.
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 want to autowire my components , but it seems I cannot figure it out. I know how to do it with #Autowired & #Qualifier using context:annotation-config in my xml. But how can I do the same job with components? My snippet is:
The component where I want to inject bean.
#Component
public class Pianist implements Performer{
private Instruments instrument;
#Autowired
public void makeInstrument(Instruments instrument) {
this.instrument = instrument;
}
#Override
public void perform() {
instrument.play();
}
My component which will be injected:
#Component
public class Piano implements Instruments{
#Override
public void play() {
System.out.println("Piano");
}
}
My xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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.city.lt">
</context:component-scan>
</beans>
My main:
ApplicationContext context = new ClassPathXmlApplicationContext("builder.xml");
Performer performer = (Performer)context.getBean("Pianist");
performer.perform();
Then I try to run it, I am getting this error:
Could not autowire method: public void com.city.lt.Pianist.makeInstrument(com.city.lt.Instruments);
What is wrong with that? Thanks
EDITED: stacktrace
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pianist': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.city.lt.Pianist.makeInstrument(com.city.lt.Instruments); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.city.lt.Instruments] is defined: expected single matching bean but found 2: [guitar, piano]
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.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.city.lt.main.main(main.java:11)
you need the #Autowired on a setter/constructor/or field.
If you chose setter, please name it like a setter
#Autowired
public void setInstrument(Instruments instrument) {
this.instrument = instrument;
}
All Beans created start with a lower case (by default):
Performer performer = (Performer)context.getBean("pianist");
The problem is that you have 2 implementations of Instrument. Spring does not know which one to chose (because it is really uncreative and doesn't care about music)
You need to tell Spring what exactly it should use. Ether by annotating one with #Primary or wire all implementations into a Collection or use the implementation class you want to wire as field type or use #Qualifier("piano") with your autowired annotation.
#Autowired
public void makeInstrument(#Qualifier("piano") Instruments instrument) {
this.instrument = instrument;
}
If you don't need the "makeInstrument" method after, it's easier this way:
#Component
public class Pianist implements Performer{
#Autowired
private Instruments instrument;
#Override
public void perform() {
instrument.play();
}
}
Take a look at the stack trace
No unique bean of type [com.city.lt.Instruments] is defined: expected single matching bean but found 2: [guitar, piano]
You have 2 classes implementing the Instruments interface. Spring, by default, when using #Autowired does this by type. As there are 2 beans of the same type it doesn't know which one to inject. (Which is also what your stack trace tells you).
To only way to make this work is to use, indeed, a #Qualifier to specify which one to inject.
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);
}