Spring Injection using #Autowired - java

I'm having a bad time trying to run my program using Spring #Autowired annotation.
Just to explain you what I'm trying to do, I have a main controller class, MainController, that always uses two other classes (SquadraController class and UserController class) to do some work.
Instead of instantiating these classes any time I need them, I decided to declare them as instance variables with the #Autowired annotation and call them any time I need them.
So I have my instance variables with #Autowired annotation and declared the beans in the context xml file, but I get the following error and I can't get out of it:
20/03/2015 15:10:00 - WARN - (AbstractApplicationContext.java:487) - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.fabrizio.fantavalcanneto.controller.UserController org.fabrizio.fantavalcanneto.controller.MainController.userController; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.fabrizio.fantavalcanneto.controller.UserController] 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:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
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:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
This is my MainController class (the snippet that raises the error):
#Controller
public class MainController {
private static final Logger logger = LoggerFactory.getLogger(MainController.class);
#Autowired
private UserController userController;
#Autowired
private SquadraController squadraController;
This is the xml file where I declare my beans (I also tried to declare MainController bean without declaring the instance variables as properties):
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="org.fabrizio.fantavalcanneto.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="userController" class="org.fabrizio.fantavalcanneto.controller.UserController" >
</bean>
<bean id="mainController" class="org.fabrizio.fantavalcanneto.controller.MainController">
<property name="userController" value="userController"></property>
<property name="squadraController" value="squadraController"></property>
</bean>
<bean id="squadraController" class="org.fabrizio.fantavalcanneto.controller.SquadraController">
</bean>
</beans>
UserController and SquadraController have no instance variables.

If you are context component scanning you don't need to define the beans in the config file, something like this will work. All you need is #Controller annoation on the relevant classes :
<context:component-scan base-package="org.fabrizio.fantavalcanneto.controller" />
// for default converters etc add this aswell
<mvc:annotation-driven/>
Just check you have the correct base package/typos

Related

java.lang.NoClassDefFoundError: org.mvel2.integration.VariableResolverFactory

I am getting this runtime error from the project
[12/5/18 11:54:35:045 EST] 00000104 XmlWebApplica W org.springframework.context.support.AbstractApplicationContext refresh Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in ServletContext resource [/WEB-INF/applicationsweb-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org.mvel2.integration.VariableResolverFactory
[12/5/18 11:54:35:048 EST] 00000104 DispatcherSer E org.springframework.web.servlet.FrameworkServlet initServletBean Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in ServletContext resource [/WEB-INF/applicationsweb-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org.mvel2.integration.VariableResolverFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
My ApplicationContext looks like this,
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Resolves views selected for rendering by #Controllers to tiles resources -->
<beans:bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver"/>
<beans:bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer" >
<beans:property name="completeAutoload" value="true"/>
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/defs/tiles-defs.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</beans:beans>
I have my spring-webmvc-4.2.6.RELEASE.jar in webInf lib as well as the EAR lib. Any suggestions please?
Error is telling that it could not find some class it means you don't have some jar where the class is located
Just add this jar file:
https://mvnrepository.com/artifact/org.mvel/mvel2

Autowiring tcp-outbound-channel-adapter using Id does not work

I am trying to autowire my tcp-inbound-channel-adapter bean defined as below. Later I will be starting this on certain conditions.
<int-ip:tcp-inbound-channel-adapter
id="inboundClient" channel="replies" connection-factory="client"
client-mode="true" auto-startup="false" retry-interval="10000" />
Autowiring as:
#Autowired
#Qualifier("inboundClient")
TcpReceivingChannelAdapter inboundClient;
My inboundClient is always null.
However when I do something as below, it works, without NPE, tc has object reference and starts the inbound adapter and receives data.
TcpReceivingChannelAdapter tc = (TcpReceivingChannelAdapter)
context.getBean("inboundClient");
Thread.sleep(5000);
tc.start();
Please let me know, if you have come across this or solved this.
EDIT:
I have my code posted here:
<?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:int="http://www.springframework.org/schema/integration"
xmlns:int-ip="http://www.springframework.org/schema/integration/ip"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/ip http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">
<context:component-scan base-package="com.tcpclient" />
<context:annotation-config />
<!--Deserializer for incoming data on the socket -->
<bean
class="org.springframework.integration.ip.tcp.serializer.ByteArraySingleTerminatorSerializer"
id="serializeAndDeserializer">
<constructor-arg type="byte" value="0" />
</bean>
<!-- TCP Client configuration -->
<!-- Channels for communication -->
<int:channel id="tcp-client-input" />
<int:channel id="message" />
<int:channel id="message-serviceActivator" />
<int:gateway id="gateway" service-interface="com.tcpclient.ClientGateway"
default-request-channel="tcp-client-input" default-reply-channel="message" />
<int-ip:tcp-connection-factory id="clientFactory"
type="client" host="10.255.233.21" port="1234" single-use="false"
so-timeout="10000" deserializer="serializeAndDeserializer" serializer="serializeAndDeserializer" />
<int-ip:tcp-outbound-channel-adapter
id="outBoundClient" channel="tcp-client-input" connection-factory="clientFactory"
retry-interval="60000" auto-startup="false" />
<int-ip:tcp-inbound-channel-adapter
id="inBoundClient" channel="message" connection-factory="clientFactory"
client-mode="true" auto-startup="false" retry-interval="60000" />
<int:object-to-string-transformer
input-channel="message" output-channel="message-serviceActivator" />
<int:service-activator input-channel="message-serviceActivator"
method="onRtlsMessageArrival">
<bean class="com.tcpclient.HandleRtlsMessage" />
</int:service-activator></beans>
Config manager:
#component
public class RtlsConfigManager {
#Autowired
#Qualifier("inBoundClient")
TcpReceivingChannelAdapter inboundClient;
#Autowired
#Qualifier("outBoundClient")
TcpSendingMessageHandler outBoundClient;
public void initialize(Boolean canStart) {
try {
if (canStart) {
inboundClient.start();
outBoundClient.start();
}
} catch (Exception e) {
logger.error("Error occured while fetching data.");
}
}
}
Stack trace
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.integration.ip.tcp.TcpSendingMessageHandler] 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=outBoundClient)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
If I take off below from existing code
#Autowired
#Qualifier("outBoundClient")
TcpSendingMessageHandler outBoundClient;
and
outBoundClient.start();
it starts my inBoundClient
Am I trying to autowire outBoundClient in a wrong way. Please let me know if you need more details.
You should inject these beans with type SmartLifeCycle not the TcpSendingMessageHandler type. The receiving adapter will work that way, though but since you want to use the lifecycle stuff it's better to narrow the type.
The sending handler actually has a bean name outBoundClient.handler but that's not what you want to start/stop, it is wrapped in a consumer (which implements SmartLifecyle and the type depends on the channel type; in this case, an EventDrivenConsumer).

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

I've been getting this exception in the console.I tried a lot and could not resolve the issue
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reportsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private main.java.com.shc.mso.service.VendorService main.java.com.shc.mso.controllers.ReportsController.vendorsservice; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [main.java.com.shc.mso.service.VendorService] 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:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4760)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5184)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private main.java.com.shc.mso.service.VendorService main.java.com.shc.mso.controllers.ReportsController.vendorsservice; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [main.java.com.shc.mso.service.VendorService] 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:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [main.java.com.shc.mso.service.VendorService] 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:1100)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 24 more
I tried looking at all the answers but could not figure out the solution.
ReportsController.class
package main.java.com.shc.mso.controllers;
import java.util.ArrayList;
import java.util.List;
import main.java.com.shc.mso.model.PandLReport;
import main.java.com.shc.mso.model.Vendor;
import main.java.com.shc.mso.service.PandLService;
import main.java.com.shc.mso.service.VendorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.google.gson.Gson;
/*
*
* This is the Reports controller class.
* It invokes several methods present in Service layer; which in turn invokes methods present in DAO layer.
* It contains methods which creates jqGrid data, models, validations etc.
*
* */
#Controller
public class ReportsController {
//Logger myLog = LogManager.getLogger(ReportsController.class);
#Autowired
private VendorService vendorsservice;
#RequestMapping(value="/pandlreport", method = RequestMethod.GET)
public ModelAndView listEmployees() {
Gson gson = new Gson();
List list=new ArrayList<String>();
for (Vendor v:vendorsservice.listVendors()){
String json = new String();
json = gson.toJson(v);
list.add(json);
}
System.out.println(list.toArray());
ModelAndView modelAndView = new ModelAndView("employeesList");
modelAndView.addObject("employeesList", list);
System.out.println(modelAndView);
return modelAndView;
}
}
VendorService.class
package main.java.com.shc.mso.service;
import java.util.ArrayList;
import main.java.com.shc.mso.model.Vendor;
public interface VendorService{
public ArrayList<Vendor> listVendors();
}
VendorServiceImpl.class
package main.java.com.shc.mso.service;
import java.util.List;
import main.java.com.shc.mso.dao.VendorDao;
import main.java.com.shc.mso.model.Vendor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service("vendorService")
#Transactional
public class VendorServiceImpl {
#Autowired(required=true)
private VendorDao vendorDao;
#Transactional
public List<Vendor> listVendors(){
return vendorDao.listVendors();
}
}
Spring.xml
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Activates various annotations to be detected in bean classes -->
<mvc:annotation-driven />
<context:component-scan base-package="main.java.com.shc.mso.controllers" />
<context:component-scan base-package="main.java.com.shc.mso.dao" />
<context:component-scan base-package="main.java.com.shc.mso.model" />
<context:component-scan base-package="main.java.com.shc.mso.service" />
<context:component-scan base-package="main.java.com.shc.mso.util" />
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="login"/>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- View Resolver for Excel Documents -->
<bean id="nonJSPViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="0" />
<property name="location" value="/WEB-INF/spring/spring-excel-views.xml" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<!-- Use SpringException when it is invoked-->
<!-- Use defaultErrorView when any other exception occurs -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.shc.mso.util.SpringException">
ExceptionPage
</prop>
</props>
</property>
<property name="defaultErrorView" value="error"/>
</bean>
</beans>
import main.java.com.shc.mso.dao.VendorDao;
import main.java.com.shc.mso.model.Vendor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service("vendorService")
#Transactional
public class VendorServiceImpl {
#Autowired(required=true)
private VendorDao vendorDao;
#Transactional
public List<Vendor> listVendors(){
return vendorDao.listVendors();
}
}
fix VendorServiceImpl as following
#Service
public class VendorServiceImpl implements VendorService{
#Autowired
private VendorDao vendorDao;
#Transactional
public List<Vendor> listVendors(){
return vendorDao.listVendors();
}
}
then in controller use
#Autowired
VendorService vendorService;
and call method as
vendorService.listVendors();
and in spring xml keep only the following line. you dont need all five
<context:component-scan base-package="main.java.com.shc.mso" />
As exception suggest NoSuchBeanDefinitionException: No qualifying bean of type [main.java.com.shc.mso.service.VendorService] found, you didn't annotate VendorService class as a service which could be register with spring container.
I guess this is just a simple mistake VendorServiceImpl should implement the VendorService interface.
#Autowire is done by type and in the code above VendorServiceImpl is not of type VendorService
See also
Inject and Resource and Autowired annotations

Why is my Spring data configuration not autowiring a repository interface?

First of all, I would like to welcome you all, although I'm a new member I'm an often anonymous user searching for possible answers to my problems here :)
I have a really wired problem with my Spring Data configuration, with which I've been battling for 2 days non and now possibilities come to mind ;/
I have created before projects with Spring Data JPA functionality and didn't have that much of problems with it like now...;/
In this process I've researched multiple web sites and done a bit of changing in my configuration but nothing helped;/
In my spring config xml file, I've created the following beans : BasicDataSource, LocalContainerEntityManagerFactoryBean and a JpaTransactionManager one.
BTW:
I'm using Spring 4.1.6, Spring Data release 1.8.0 and hibernate 4.3.8.Final
Here is the Spring config file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.7.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<context:component-scan base-package="pl.mmalik.portlet.common.model" />
<context:component-scan base-package="pl.mmalik.portlet.common.service" />
<context:annotation-config />
<context:property-placeholder location="classpath:springData/dataSource.properties"/>
<util:properties id="hibernateProperties" location="classpath:springData/hibernate.properties"/>
<bean id="lifeRayDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${connection.driverClassName}"/>
<property name="url" value="${connection.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="maxActive" value="128"/>
<property name="maxIdle" value="64"/>
<property name="minIdle" value="24"/>
<property name="validationQuery" value="SELECT 1 FROM DUAL"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="lifeRayDataSource"/>
<property name="packagesToScan">
<list>
<value>pl.mmalik.portlet.common.domain.model</value>
</list>
</property>
<property name="persistenceUnitName" value="LIFE-RAY-PU" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties" ref="hibernateProperties"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" primary="true">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<jpa:repositories
base-package="pl.mmalik.portlet.common.respository"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager" />
</beans>
I'm trying to create a JpaRepository interface that will handle basic db operations on an entity.
The entity is as follows:
#Entity
#Table(name = "Recipie")
public class Recipie {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "RecipiSeq")
#SequenceGenerator(initialValue = 1,
name = "RecipiSeq",
sequenceName = "RecipiSeq",
allocationSize = 1)
#Column(name = "RECIPIE_ID", unique = true)
private Integer recipieId;
#NotNull
#Column(name = "RECIPIE_NAME")
private String name;
#NotNull
#Column(name="RECIP_CAT")
private String category;
#NotNull
#Size(max = 255)
#Column
private String description;
#Digits(fraction = 0, integer = 3)
#Column(name = "READY_IN")
private Integer readyIn;
#Column
private String author;
#Column(name="iconFile")
private byte[] file;
public Recipie() {
}
// Setters and getters are here...
}
The Repository is a small interface extending JpaRepository,
public interface RecipieRepository extends JpaRepository<Recipie, Integer>{
}
On deploy I'm getting a "NoSuchBeanDefinitionException" with the following stacktrace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'recipieMock': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private pl.mmalik.portlet.common.repositories.RecipieRepository pl.mmalik.portlet.common.domain.model.mock.RecipieMock.recipieRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pl.mmalik.portlet.common.repositories.RecipieRepository] 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:1210)
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.portlet.FrameworkPortlet.createPortletApplicationContext(FrameworkPortlet.java:368)
at org.springframework.web.portlet.FrameworkPortlet.initPortletApplicationContext(FrameworkPortlet.java:297)
at org.springframework.web.portlet.FrameworkPortlet.initPortletBean(FrameworkPortlet.java:271)
at org.springframework.web.portlet.GenericPortletBean.init(GenericPortletBean.java:124)
at javax.portlet.GenericPortlet.init(GenericPortlet.java:107)
at com.liferay.portlet.InvokerPortletImpl.init(InvokerPortletImpl.java:269)
at com.liferay.portlet.PortletInstanceFactoryImpl.init(PortletInstanceFactoryImpl.java:228)
at com.liferay.portlet.PortletInstanceFactoryImpl.create(PortletInstanceFactoryImpl.java:145)
at com.liferay.portlet.PortletInstanceFactoryUtil.create(PortletInstanceFactoryUtil.java:41)
at com.liferay.portlet.PortletBagFactory.create(PortletBagFactory.java:337)
at com.liferay.portal.deploy.hot.PortletHotDeployListener.doInvokeDeploy(PortletHotDeployListener.java:370)
at com.liferay.portal.deploy.hot.PortletHotDeployListener.invokeDeploy(PortletHotDeployListener.java:125)
at com.liferay.portal.deploy.hot.HotDeployImpl.doFireDeployEvent(HotDeployImpl.java:227)
at com.liferay.portal.deploy.hot.HotDeployImpl.fireDeployEvent(HotDeployImpl.java:96)
at com.liferay.portal.kernel.deploy.hot.HotDeployUtil.fireDeployEvent(HotDeployUtil.java:28)
at com.liferay.portal.kernel.servlet.PluginContextListener.fireDeployEvent(PluginContextListener.java:164)
at com.liferay.portal.kernel.servlet.PluginContextListener.doPortalInit(PluginContextListener.java:154)
at com.liferay.portal.kernel.util.BasePortalLifecycle.portalInit(BasePortalLifecycle.java:44)
at com.liferay.portal.kernel.util.PortalLifecycleUtil.register(PortalLifecycleUtil.java:74)
at com.liferay.portal.kernel.util.PortalLifecycleUtil.register(PortalLifecycleUtil.java:58)
at com.liferay.portal.kernel.util.BasePortalLifecycle.registerPortalLifecycle(BasePortalLifecycle.java:54)
at com.liferay.portal.kernel.servlet.PluginContextListener.contextInitialized(PluginContextListener.java:116)
at com.liferay.portal.kernel.servlet.SecurePluginContextListener.contextInitialized(SecurePluginContextListener.java:151)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3954)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:426)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1345)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private pl.mmalik.portlet.common.repositories.RecipieRepository pl.mmalik.portlet.common.domain.model.mock.RecipieMock.recipieRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pl.mmalik.portlet.common.repositories.RecipieRepository] 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)
... 44 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pl.mmalik.portlet.common.repositories.RecipieRepository] 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)
... 46 more
I'm thinking this has something to do with my configuration of the EntityManager or DataSource, but researching other options of configuration these elements didn't gave me anything good ;/
I would be very grateful for any suggestions, I'm totally stuck on this.
If you need any additional information on the configuration I will update this post.
If the problem had to do with DataSource or EntityManager, you would have a message informing you about a problem with those. But you don't. The message you get is
No qualifying bean of type [pl.mmalik.portlet.common.repositories.RecipieRepository] found
So that means that Spring can't find any Spring bean implementing this interface. Have you configured Spring to scan that package?
<jpa:repositories
base-package="pl.mmalik.portlet.common.respository"
No, you haven't.
It seems there are NO implementations for your interface 'RecipieRepository', but somewhere in your code you have used #Autowired filed to that 'interface' like
#Autowired
private RecipieRepository recipieMock;
It will fail, because you need at least one implementation to auto wire.
To Solve the issue, Create a 'class' which implements your repository 'RecipieRepository', and add below annotations to it.
#Repository
#Transactional
#Component

Spring 4.1 #Qualifier doesnt'work

I have classes, xml configuration file and error stack trace like this. I have no idea why #Qualifier doesn't work. I see on errors that he don't even do anything.
DOG
public class SimpleDog implements Dog {
#Autowired
#Qualifier("small")
private Size size;
private String name;
public Size getSize() {
return size;
}
public void setSize(Size size) {
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public void giveSound() {
System.out.println("dog size is : width : (" + size.getWidth() + ") , height : (" + size.getHeight() + ")");
System.out.println("dog's name : " + name);
}
}
TEST CLASS
public class Test2 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-test2.xml");
SimpleDog dog = (SimpleDog) context.getBean("dog");
dog.giveSound();
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dog" class="com.tests.test2.SimpleDog">
<property name="name" value="Puppy" />
</bean>
<bean id="size1" class="com.tests.test2.Size">
<qualifier value="small"/>
<property name="height" value="2"/>
<property name="width" value="1"/>
</bean>
<bean id="size2" class="com.tests.test2.Size">
<qualifier value="large"/>
<property name="height" value="20"/>
<property name="width" value="10"/>
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
Error Stack Trace
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dog': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.tests.test2.Size com.tests.test2.SimpleDog.size; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.tests.test2.Size] is defined: expected single matching bean but found 2: size1,size2
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
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:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:140)
at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:84)
at pl.patrykgryta.test2.Test2.main(Test2.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.tests.test2.Size com.tests.test2.SimpleDog.size; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.tests.test2.Size] is defined: expected single matching bean but found 2: size1,size2
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:555)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 18 more
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.tests.test2.Size] is defined: expected single matching bean but found 2: size1,size2
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1016)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:527)
... 20 more
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dog': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.tests.test2.Size com.tests.test2.SimpleDog.size; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.tests.test2.Size] is defined: expected single matching bean but found 2: size1,size2
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
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:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:140)
at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:84)
at pl.patrykgryta.test2.Test2.main(Test2.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.tests.test2.Size com.tests.test2.SimpleDog.size; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.tests.test2.Size] is defined: expected single matching bean but found 2: size1,size2
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:555)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 18 more
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.tests.test2.Size] is defined: expected single matching bean but found 2: size1,size2
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1016)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:527)
... 20 more
Need help
Probably your ApplicationContext's BeanFactory is configured with default AutowireCandidateResolver (i.e. SimpleAutowireCandidateResolver) instead of QualifierAnnotationAutowireCandidateResolver.
In previous versions of Spring (before 4.0), QualifierAnnotationAutowireCandidateResolver was set during creation of most ApplicationContexts (compare AbstractRefreshableApplicationContext.customizeBeanFactory(DefaultListableBeanFactory) implementations).
Currently, QualifierAnnotationAutowireCandidateResolver for AppCtx is/can be applied by:
org.springframework.beans.factory.annotation.CustomAutowireConfigurer (see javadoc and implementation of postProcessBeanFactory(ConfigurableListableBeanFactory) method), e.g. add to your xml:
<bean id="customAutowireConfigurer" class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
<property name="customQualifierTypes">
<set>
<value>org.springframework.beans.factory.annotation.Qualifier</value>
</set>
</property>
<context:annotation-config /> (see: AnnotationConfigBeanDefinitionParser.parse(Element,ParserContext) and related)
#Qualifier is used to reference a bean by its name or id. Since it can't find an xml entry that has a name or id of 'small' it tries to match by type, of which it found two instances of Size.
The following would work:
<bean id="small" class="com.tests.test2.Size">
<property name="height" value="2"/>
<property name="width" value="1"/>
</bean>
Though it appears you would like to treat instances of Size as pre-configured beans. If that were the case you could declare instances of Dog in your xml file and refer to Size beans ... something like this:
<bean id="rex" class="com.tests.test2.SimpleDog">
<property name="name" value="Puppy" />
<property name="size" ref="size1"/>
</bean>
#Qualifier(name="..") annotation and give the name of the bean that we want Spring to inject
and name of your beans are size1 and size2 .
so try
#Qualifier("size1")
#Qualifier("small") means you look for a bean named "small" (bean id="small" ...) #Autowired means you look for a bean with a type that matchs.
It makes sense to use this two configurations together in some cases. It means: look for a bean named like that, and if you don't find, then look for a bean with the correct type. This can be powerful, very.
From the Spring documentation, you can declare who is "small" with an xml qualifier, as you did. But in their example there is NO id="..." I don't know if it makes sense to define both qualifier and id. So I suppose (I don't test) you can repair your example by removing the parts id="sizeX"
As says your stacktrace
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.tests.test2.Size] is defined: expected single matching bean but found 2: size1,size2
Spring can't match a single bean to inject because he find 2 beans that could using, for this reason will thrown this exception.
Exception thrown when a BeanFactory is asked for a bean instance for
which multiple matching candidates have been found when only one
matching bean was expected.
Reference of Exception
Anyway you're using this thing in the wrong way, because there isn't any bean with id="small"
You must change #Qualifier("small") to #Qualifier("size1") or #Qualifier("size2").
In Spring 4.x you should work with the following XML schema in order for this to work for you:
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"
and you should add the following tag:
<context:component-scan base-package="com.tests.test2" />
So the following XML should solve your problem (it solved mine :) ):
<?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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.tests.test2" />
<bean id="dog" class="com.tests.test2.SimpleDog">
<property name="name" value="Puppy" />
</bean>
<bean id="size1" class="com.tests.test2.Size">
<qualifier value="small"/>
<property name="height" value="2"/>
<property name="width" value="1"/>
</bean>
<bean id="size2" class="com.tests.test2.Size">
<qualifier value="large"/>
<property name="height" value="20"/>
<property name="width" value="10"/>
</bean>
</beans>
See more here.
We have struts 1.x used with Spring 3.x in our project. In the process of upgrading from spring 3->4, our qualifier annotation in the struts action does not work any more. After digging in and compare the Spring 3 and 4, finally found the reason.
reason1: QualifierAnnotationAutowireCandidateResolver is not the default resolver in spring 4
In Spring 3, after we create our beanfacotry in the application context, Spring will explicitly call :
beanFactory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
In spring 4, it is not called any more in the AbstractRefreshableApplicationContext’s
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory)
So for the parent(root) context, it should still work as is if you have the in the config xml. However for the child context the default resolver will become ‘SimpleAutowireCandidateResolver’
reason2: The child resolver is passed to parent when trying to determine ‘isAutowireCandidate()’ in Spring 4’s DefaultListableBeanFactory
The isAutowireCandidate() will delegate the responsibility to parent beanFactory if it cannot make decision.
In Spring 3, the delegation does not pass the resolver to the parent so that parent context uses its own resolver to call the isAutowireCandidate(). However in Spring 4, it changes. The resolver is passed as a parameter to the parent who uses it to call the isAutowireCandidate(). So even the parent has a ContextAnnotationAutowireCandidateResolver which extends QualifierAnnotationAutowireCandidateResolver as its resolver, it still does not help.
The #a5phyx solution should work if it is added to the child's application context xml.
Try using this bean definition in your beans.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
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
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
xmlns:context="http://www.springframework.org/schema/context">
<context:annotation-config/>
<!-- define your beans here-->
</beans>

Categories

Resources