How do I inject a Class[] array in spring? - spring

I've got a class which has a static method newInstance(Class[] classes, List properties), and I need Spring to be able to instantiate instances using this class.
What i've got so far in my XML configuration is :
<bean id="jaxbContext" scope="prototype" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
<constructor-arg>
<list>
<value type=">com.company.pas.entity.Partner.class</value>
</list>
</constructor-arg>
<constructor-arg>
<list>
<value>com/company/pas/entity/mapping/partner-pojo2xml.xml</value>
</list>
</constructor-arg>
</bean>
This throws the below exception. Note that it complains that it can't find the newInstance method, but i assume that is because it can't find a newInstance method with a signature which matches the configuration. I suspect that Spring interprets the list of classes as java.lang.String, and not Class.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jaxbContext' defined in class path resource [com/company/pas/context/mappingContext.xml]: No matching factory method found: factory method 'newInstance'. Check that a method of the specified name exists and that it is static.
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:500)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:964)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:870)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:479)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
... 46 more
How do I get spring to inject an array of Class[] based on a configuration file?

JAXBContext.newInstance() has this overload:
newInstance(String contextPath)
newInstance(String contextPath,ClassLoader classLoader)
newInstance(Class... classesToBeBound)
newInstance(Class[] classesToBeBound,Map<String,?> properties)
newInstance(String contextPath,ClassLoader classLoader,Map<String,?> properties)
To be honest I can't find a newInstance(Class[] classes, List properties) overload so spring is right when tells you it can't find the newInstance() method

Related

With constructor autowiring Spring does not throw an exception when there are multiple implementation types

There are interfaces Work and You. There are implementation types WorkImpl and YouImpl and YouImpl2.
I use constructor autowire to inject a You implementation instance in a WorkImpl instance.
Because there are multiple You implementations types, I thought Spring would throw an exception. But Spring instantiates an instance of one of the implementation types, in my case it was YouImpl. This is what I do not understand.
The configuration file is partly,
<bean
id="work"
class="my.test.own.spring_book.WorkImpl"
autowire="constructor"
>
<property name="age" value="52"/>
<property" name="name" value="Foo Bar"></property>
</bean>
<bean
id="you"
class="my.test.own.spring_book.YouImpl"
>
</bean>
<bean
id="you2"
class="my.test.own.spring_book.YouImpl2"
>
</bean>
WorkImpl has one constructor,
public WorkImpl(You you) {
this.you=you;
}
There are few types of autowiring using configuration approach:
byName
byType
constructor
autodetect:- Similar to byType, but type applies to constructor arguments.
Spring container looks at the constructor of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file.
<bean id="you" class="my.test.own.spring_book.YouImpl">
</bean>
<bean id="you2" class="my.test.own.spring_book.YouImpl2">
</bean>
It will match with you as name of parameter used in constructor is you
public WorkImpl(You you) {
this.you=you;
}
In order to avoid this you can use autowire-candidate="false" hence that bean will not take part in autowiring
<!-- This bean will not be injected-->
<bean id="you" class="my.test.own.spring_book.YouImpl" autowiring-candidate="false">
</bean>
<bean id="you2" class="my.test.own.spring_book.YouImpl2">
</bean>
Above is the answer of your question. But I will try to explain more so I can use this answer for future if I forget.
Now suppose you don't give id attribute to the bean or value of id attribute is different than the constructor parameter name.
<bean id="you1" class="my.test.own.spring_book.YouImpl" autowiring-candidate="false">
</bean>
<bean id="you2" class="my.test.own.spring_book.YouImpl2">
</bean>
Spring container searches any bean with type You, yes found two. Do next step
Spring container sees any bean with name(i.e id="you") you. No
It throws exception Unsatisfied dependency Injection
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'work' defined in class path resource [autowire-contructor.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type
[my.test.own.spring_book.You]: : No unique bean of type [my.test.own.spring_book.You] is defined: expected single matching bean but found 2: [you1, you2]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException

custom thymeleaf dialect registration causing exception

in applicationContext.xml
<bean id="templateEngine"
class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean class="org.test.custom.CustomDialact" />
</set>
</property>
</bean>
Stacktrace:
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'additionalDialects' of bean class [org.thymeleaf.spring3.SpringTemplateEngine]: Bean property 'additionalDialects' 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:1042)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:902)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:57)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1424)
... 50 more
i don't know but it was fixed after restarting machine. but mean while i find another solution
by extend a custom class with HashSet and in constructor add custom dialect in it and declare it in xml. provide it reference to additionalDialects . thats it .it will start running . it think it is problem related to generics as spring sometimes supply empty type
like HashSet<V> .

Is default constructor required in Spring injection?

I'm trying to inject a constructor that takes some arguments. After compiling Spring complains it couldn't find a default constructor (I haven't defined it) and throws BeanInstatiationException and NoSuchMethodException.
After defining a default constructor the exceptions don't appear anymore, however my object is never initialized with the argument constructor, only the default one is called. Does Spring really require a default constructor in this case? And if yes, how can I make it use the argument constructor instead of the default one?
This is how I wire everything:
public class Servlet {
#Autowired
private Module module;
(code that uses module...)
}
#Component
public class Module {
public Module(String arg) {}
...
}
Bean configuration:
<beans>
<bean id="module" class="com.client.Module">
<constructor-arg type="java.lang.String" index="0">
<value>Text</value>
</constructor-arg>
</bean>
...
</beans>
Stack trace:
WARNING: Could not get url for /javax/servlet/resources/j2ee_web_services_1_1.xsd
ERROR initWebApplicationContext, Context initialization failed
[tomcat:launch] org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'module' defined in URL [...]: Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Could not
instantiate bean class [com.client.Module]: No default constructor found; nested
exception is java.lang.NoSuchMethodException: com.client.Module.<init>()
Spring only "requires" a default constructor if you plan on instantiating it without any arguments.
for example, if your class is like this;
public class MyClass {
private String something;
public MyClass(String something) {
this.something = something;
}
public void setSomething(String something) {
this.something = something;
}
}
and you set it up in Spring like this;
<bean id="myClass" class="foo.bar.MyClass">
<property name="something" value="hello"/>
</bean>
you're going to get an error. the reason is that Spring instantiates your class new MyClass() then tries to set call setSomething(..).
so instead, the Spring xml should look like this;
<bean id="myClass" class="foo.bar.MyClass">
<constructor-arg value="hello"/>
</bean>
so have a look at your com.client.Module and see how its configured in your Spring xml
Most probably you are using component-scanning and since you define annotation #Component for class Module it tries to instantiate the bean. You do not need #Component annotation if You are using XML for bean definition.
Just faced the same problem, i guess till now you might have solved the problem.
Below is what you could have changed your bean configuration to,
<bean id="module" class="com.client.Module">
<constructor-arg value="Text"/>
</bean>

How can i use a specific proprety for each bean call in Spring

I'm developing an application using spring . I have a bean that i need to call multiple times but for each call i need to change the properties values dynamically . Is there a way to do this .
I had an idea to set the bean properties as an array ,in eatch array i put the parameters that i want to use . For example array[0] contains the params of the first call , array[1] params of the second call,... is it possible to do that ?
Here is a code sample :
<bean class="Dummy2">
<!-- or a list of values -->
<property name="foos">
<util:list>
<value>A,b,c</value>
<value>X,y,z</value>
<value>1,2,3</value>
<value>7,8,9</value>
</util:list>
</property>
</bean>
the setter
#Override
public void setFoo(list<String[]> args) {
...
}
If any one have a better idea or a usefull idea i will be grateful
Thank You
This is the propreties of the bean that calls the beans
<property name="activities">
<list>
<ref bean="1"/> //Calling bean 1
<ref bean="2"/> //Calling bean 2
<ref bean="1"/> //Calling bean 1 again
<ref bean="2"/>//Calling bean 2 again
<ref bean="2"/>
</list>
</property>
i need to use different parameters for each call (call the setter with different values)
Would using Spring's PostConstruct annotation on an initialiser method on your 'master' bean be useful? You could use simple setter methods to inject both the list of beans and the list of configurations into the master bean, and in the init method (annotated with #PostConstruct) configure each bean correctly.
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-postconstruct-and-predestroy-annotations
Are you familiar with AOP you can use aspect to do this using #Before Advice to set your method properties before calling it

Creating a Spring Bean using FactoryMethod with variable arguments from Spring?

How can we create a bean using FactoryMethod with variable arguments.
public class ConnectionFactoryClass {
public static Connection composeConnection(final Property... properties) {
...
}
}
bean.xml
<bean id="Connection"
class="com.example.ConnectionFactoryClass"
factory-method="composeConnection"
scope="singleton">
<constructor-arg ref="Driver"/>
<constructor-arg ref="Pool"/>
</bean>
Spring is giving me an error saying,
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Connection' defined in file [./beans.xml]: No matching factory method found: factory method 'composeConnection'
Try the following:
<bean id="Connection"
class="com.example.ConnectionFactoryClass"
factory-method="composeConnection"
scope="singleton">
<constructor-arg>
<array>
<bean ref="Driver" />
<bean ref="Pool" />
</array>
</constructor-arg>
</bean>
I think you are having a problem because the JVM turns a var arg params into an Object Array and you need to pass in a single paramater to the constructor which is the array of objects. I have not tried the above xml so I might have typos in it, but something like the above should work.

Resources