Why ambiguity when I inject argument for multiple constructors? - java

Why does this happen when I define two constructors, one of which has referenced parameter, and another a primitive parameter?
Below are relevant snippets.
Constructor 1:
public TextEditor(SpellChecker sc) {...}
Constructor 2:
public TextEditor(int editorNum) {...}
bean definition xml file:
...
<constructor-arg ref="spellChecker"/> <!--spellChecker is defined as class elsewhere-->
<constructor-arg value="100"/>
...
Compiling error of ambiguities remains even when I add type/name/index to the tag.
post full stack trace below
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'textEditor' defined in class path resource [Beans.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
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.tutorialspoint.MainApp.main(MainApp.java:7)

Proper constructor injection through applicationContext.xml will be like this :
For example : Suppose your TextEditor & SpellChecker classes are in the package com.test.
Now, the xml will look 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">
<!-- Create a SpellChecker bean -->
<bean id = "spellChecker" class="com.test.SpellChecker"/>
<!-- Create a TextEditor bean by calling the first constructor -->
<bean id="textEditor" class="com.test.TextEditor" >
<constructor-arg ref="spellChecker"/>
</bean>
<!-- Create a TextEditor bean by calling the second constructor -->
<bean id="textEditor_1" class="com.test.TextEditor" >
<constructor-arg value="100"/>
</bean>
</beans>
Hope this helps you :)
Thanks.

Related

Spring Injection using #Autowired

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

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>

Error while Trying to keep a list of message properties file in spring

I tried to create Message source based on the tutorials in java brains, I ran into a problem while trying to put the option to have more than one message properties file an error was produced, the error is given below
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageSource' defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.lang.String' for property 'basename'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.util.ArrayList] to required type [java.lang.String] for property 'basename': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:755)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:413)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.app.main(app.java:20)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.lang.String' for property 'basename'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.util.ArrayList] to required type [java.lang.String] for property 'basename': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:481)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:518)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1371)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1330)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 10 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.util.ArrayList] to required type [java.lang.String] for property 'basename': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:233)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:466)
The spring.xml file is given below
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" xmlns:context="http://www.springframework.org/schema/context">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
<context:annotation-config/>
<context:component-scan base-package="test"/>
When i removed the list tag from the above code the i was able to run without exception. the void main is given below.
public static void main(String args[]) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(context.getMessage("greeting", null, "hiiiii", null));
}
I have created a file mymessages.prperties with on key value pair that is greeting. Please help me find what i did wrong in this.
You are using <property name="basename"> that should be for single resource..
But for multiple resources you shoud use <property name="basenames">..
your error message clearly states that, can't covert from string to List.. you are using string type but passing list type.. so use basenames..
Hope it helps...
Change this line:
<property name="basename">
to:
<property name="basenames">
^

Spring MVC no default constructor found?

I'm having problems with my Spring controllers - I'm getting no default constructor found - but they do have a constructor which I am trying to created via the applicationContext.xml - heres the relevant bit:
<bean id="PcrfSimulator" class="com.rory.services.pcrf.simulator.PcrfSimulator" init-method="start">
</bean>
<bean id="CacheHandler" class="com.rory.services.pcrf.simulator.handlers.CacheHandler">
<constructor-arg index="0" type="com.rory.services.pcrf.simulator.CustomGxSessionIdCacheImpl">
<bean factory-bean="PcrfSimulator" factory-method="getGxSessionIdCache">
</bean>
</constructor-arg>
</bean>
Ie. I'm creating a bean first, and then trying to pass the result of a method call from that bean into the second bean's (CacheHandler) constructor.
Here'e the start of CacheHandler:
#Controller
public class CacheHandler {
private final CustomGxSessionIdCacheImpl gxSessionIdCache;
public CacheHandler(CustomGxSessionIdCacheImpl gxSessionIdCache) {
this.gxSessionIdCache = gxSessionIdCache;
}
Here's the error I'm getting:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cacheHandler' defined in URL [jar:file:/users/rtorney/Documents/apache-tomcat-7.0.25/webapps/PCRFSimulator-4.0/WEB-INF/lib/PCRFSimulator-4.0.jar!/com/rory/services/pcrf/simulator/handlers/CacheHandler.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.rory.services.pcrf.simulator.handlers.CacheHandler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.rory.services.pcrf.simulator.handlers.CacheHandler.<init>()
Any help is much appreciated!
You should either define your beans in xml or annotate them, not both (if only to avoid errors like the one you're getting).
The problem here is that you're not autowiring constructor args, so spring doesn't know what to do with your controller. It knows it has to create a bean (#Controller annotation), but it doesn't know how (no default, nor autowired constructor).
You can try to do something like:
#Controller
public class CacheHandler {
private final CustomGxSessionIdCacheImpl gxSessionIdCache;
#Autowired
public CacheHandler(CustomGxSessionIdCacheImpl gxSessionIdCache) {
this.gxSessionIdCache = gxSessionIdCache;
}
and then in xml:
<bean id="gxSessionIdCache"
factory-bean="PcrfSimulator"
factory-method="getGxSessionIdCache"/>
So it will autowire constructor parameters.
Another option is to simply create default constructor and autowire gxSessionIdCache property.
You have to add an empty default constructor :
#Controller
public class CacheHandler {
private final CustomGxSessionIdCacheImpl gxSessionIdCache;
#Autowired
public CacheHandler(CustomGxSessionIdCacheImpl gxSessionIdCache) {
this.gxSessionIdCache = gxSessionIdCache;
}
But be carefull, because it seems that you are mixing annotation based configuration (#Controller) and XML configuration. In the example above, it uses the annotation based config (so please remove the bean declaration from your XML file).
You can also get this error if you haven't activated Spring's annotation-based config. Include this in your Spring Xml:
<context:annotation-config/>
Other posters have pointed out that you can get problems if you mix autowiring/component-scanning with explicit instantiation of beans. I had a similar problem with a web application that did that. I was able to fix the problem by telling the component-scanner not to automatically instantiate a bean of the crucial class. Like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=...>
<aop:aspectj-autoproxy />
<import resource="repository.xml" />
...
<context:component-scan base-package="com.example.webserver">
<context:exclude-filter type="regex" expression="MyRepositoryImpl" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository" />
</context:component-scan>
</beans>
where repository.xml included the explicit bean instantiation:
<beans xmlns=...>
<bean id="password" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/comp/env/store/clientPassword" />
</bean>
<bean id="repository" class="com.example.webserver.datalayer.MyRepositoryImpl">
<constructor-arg ref="password" />
</bean>
...
</beans>

Need help setting up properties for ActiveDirectoryLdapAuthenticationProvider

My properties no longer work with spring.
The error I get is:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ldapActiveDirectoryAuthProvider' defined in class path resource [application-context-security.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'user-search-base' of bean class [org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider]: Bean property 'user-search-base' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
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.wm.Ldap.AuthenticationExample.main(AuthenticationExample.java:38)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'user-search-base' of bean class [org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider]: Bean property 'user-search-base' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1064)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperI
mpl.java:924)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
... 13 more
Here is my code:
<bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="someurl" />
<constructor-arg value="ldaps://someurl" />
<property name="user-search-base" value=""/>
<property name="user-search-filter" value="(sAMAccountName={0})"/>
<property name="group-search-base" value="ou=blahblah"/>
<property name="group-search-filter" value="member={0}"/>
<property name="role-prefix" value="ROLE_"/>
<property name="user-details-class" value="person"/>
</bean>
All the property names you've specified are invalid, property names cannot have dashes in them (since they map to setters).
"user-search-base" should contain somethig like
"OU=myou,dc=xx,dc=yy"

Categories

Resources