How to reduce duplication in Spring application context - java

I have some beans which I create which all use a similar pattern for bean instantiation. The top objects are all very similar, but the objects they contain differ by string constructor arguments. Everything in the each top-level bean is the same except for two instances of THIS CHANGES A and one instance of THIS CHANGES B. Below is one of my beans. The others are exactly the same except for the THIS CHANGES values.
<bean id="mover1" class="CustomDataMover">
<constructor-arg ref="session"/>
<constructor-arg>
<bean class="DataCache">
<constructor-arg>
<bean class="AllValuesReader">
<constructor-arg ref="databaseConnector"/>
<constructor-arg value="THIS CHANGES A"/>
<constructor-arg value="v1"/>
<constructor-arg value="v2"/>
</bean>
</constructor-arg>
</bean>
</constructor-arg>
<constructor-arg ref="customUpdate"/>
<constructor-arg value="THIS CHANGES B"/>
<constructor-arg>
<bean class="ValueGenerator">
<constructor-arg>
<bean class="LatestValueRetriever">
<constructor-arg ref="databaseConnector"/>
<constructor-arg value="v3"/>
<constructor-arg value="v4"/>
<constructor-arg value="THIS CHANGES A"/>
</bean>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
How can I reduce the amount of duplication in my beans? I'm looking for some way to make some sort of template. Also, please note that I do have references to other beans.

You can use abstract bean definitions as templates to reduce duplication. For example:
<bean id="parent" abstract="true">
<constructor-arg value="ARG0"/>
<property name="propertyA" value="A"/>
<property name="propertyB" value="B"/>
<property name="propertyC" ref="beanC"/>
</bean>
<bean id="child1" class="SomeClass" parent="parent">
<property name="propertyD" value="D1"/>
</bean>
<bean id="child2" class="SomeOtherClass" parent="parent">
<property name="propertyD" value="D2"/>
</bean>
Beans "child1" and "child2" will share values from "parent" for arg0, "propertyA", "propertyB", and "propertyC", and still be able to configure their own values for "propertyD".
Note that "parent" has no class and therefore cannot be instantiated. Also note that "child1" and "child2" can be children of the same abstract bean definition while being completely different classes - this hierarchy has nothing to do with the class hierarchy.

Related

How to declare the spring bean during its initialization

I need to do something like this.
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.example.Converter1"/>
<bean class="com.example.Converter2"/>
<bean id="converter3" class="com.example.Converter3"/>
<bean id="converter4" class="com.example.Converter4">
<property name="conversionService" ref="converter3"/>
</bean>
<bean id="converter5" class="com.example.Converter5">
<property name="conversionService" ref="converter4"/>
</bean>
</set>
</property>
</bean>
I want to use converter3 bean into converter4 bean via #Autowired annotation. Can I do this or it is bad way for programming?
Please, help me to solve this problem?
It's not 100% clear what you want, but in case you mean to inject instance of converter3 into converter4 class using #Autowired it's OK.

How to use javax.inject Provider<T> within spring xml configuration

I have a class called let's say A with such a setter:
//class A
#Inject
public void setAProvider(Provider<B> b)
{
this.b = b;
}
It works fine with javax.inject and annotation configuration when I want to have only one kind of A instance..
My problem is that I want to have two instances of class A, one with Provider<B1> and second with Provider<B2>. My question is how to express my requirements in Spring xml configuration?
Actually, it is briefly answered here, you need ProviderCreatingFactoryBean .
This is an example :
<bean id="a" class="a.b.b.A" scope="prototype">
<property name="xxx" value="15000"/>
</bean>
<bean id="b" class="a.b.b.B" scope="prototype">
<property name="zzz" value="-1"/>
</bean>
<bean id="providerOfA" class="org.springframework.beans.factory.config.ProviderCreatingFactoryBean">
<property name="targetBeanName" value="a"/>
</bean>
<bean id="providerOfB" class="org.springframework.beans.factory.config.ProviderCreatingFactoryBean">
<property name="targetBeanName" value="b"/>
</bean>
<bean id="barServiceA" class="a.b.c.BarService">
<property name="provider" ref="providerOfA"/>
</bean>
<bean id="barServiceB" class="a.b.c.BarService">
<property name="provider" ref="providerOfB"/>
</bean>

Common value configuration in Spring XML

I have several Spring beans in which one of the property value for all of them are same String value. Is there a way where I can define this String in XML at one place and refer it in all beans at property value settings?
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="someValue"></property>
<property name="commonProperty" value="commonValue"></property>
<bean id="nextBean" class="test.NextBean">
<property name="property2" ref="someValue"></property>
<property name="commonProperty" value="commonValue"></property>
How to set commonValue in a seperate place and refer it in both places?
Try like this.
<bean id="commonConfig" abstract="true">
<property name="commonField" value="CommonValue"></property>
</bean>
<bean id="class1" class="com.dataclass.Class1" parent="commonConfig">
<property name="field1" value="value1"></property>
</bean>
<bean id="class2" class="com.dataclass.Class2" parent="commonConfig">
<property name="field2" value="value2"></property>
</bean>
Class1 & Class2 having one common field name "commonField", parent attribute is use for this common purpose only.
In Spring this is called bean definition inheritance(this is not java class inheritance, above example Class1 & n Class not inheriting in their respective java file.)
For more detail, look at Spring doc's link.
I've never tried it before, but this should work
<bean id="commonProp" class="java.lang.String">
<constructor-arg name="original" value="yourString"></constructor-arg>
</bean>
Then, in every bean you need to reference it:
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="someValue"></property>
<property name="commonProperty" ref="commonProp"></property>
</bean>
You can define your string properties in some "init_constants.properties" file. Then you should load properties file in spring xml:
<bean id="properties"
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
<value>classpath:mail.properties</value>
<value>classpath:init_constants.properties</value>
</list>
</property>
</bean>
And after that you can inject this properties using xml:
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="{$prop1}"></property>
<property name="commonProperty" value="commonValue"></property>
</bean>
or in code using #Value annotation:
#Value(value="${prop1}")
private String property1;
Well If commonValue is string then you can put it in properties file and read it using #Value annotation.

Is there a shorthand for creating a String constant in Spring context XML file?

I need to define a string value in Spring context XML file that is shared by multiple beans.
This is how I do it:
<bean id="aSharedProperty" class="java.lang.String">
<constructor-arg type="java.lang.String" value="All beans need me :)"/>
</bean>
Creating a java.lang.String bean by passing a constructor argument of java.lang.String seems kludgy.
Is there a shortcut?
I know this property can be passed using PropertyOverrideConfigurer, but I want to keep this property within the XML file.
You can use PropertyPlaceholderConfigurer and keep values in xml:
<context:property-placeholder properties-ref="myProperties"/>
<bean id="myProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="aSharedProperty">All beans need me :)</prop>
</props>
</property>
</bean>
Then you reference it with:
<bean id="myBean" class="my.package.MyClass">
<property name="someField" value="${aSharedProperty}"/>
</bean>
A shorthand to the solution proposed by mrembisz goes like this:
<context:property-placeholder properties-ref="myProperties"/>
<util:properties id="myProperties">
<prop key="aSharedProperty">All beans need me :)</prop>
</util:properties>
You may be able to use the following:
<bean id="abstractParent" abstract="true">
<property name="sharedProperty" value="All child beans need me" />
</bean>
<bean id="bean1" class="MyClass1" parent="abstractParent">
...non-shared properties...
</bean>
<bean id="bean2" class="MyClass2" parent="abstractParent">
...non-shared properties...
</bean>
However, that relies on the property having the same name, so may not be applicable for you.
Something I've used in the past is SpEL to make sure that a bean has the same value as another:
<bean id="myBean" class="xxx.yyy.Foo" >
<property name="myProperty" value="1729" />
</bean>
<bean id="copyCat" class="xxx.yyy.Bar" >
<property name="anotherProperty" value="#{myBean.myProperty}" />
</bean>
I have found this to be particularly useful when setting the value did something other than a simple assignment.

Declaring an array of objects in a Spring bean context

I'm trying to create an array of objects in a Spring context file so I can inject it to a constructor that's declared like this:
public RandomGeocodingService(GeocodingService... services) { }
I'm trying to use the <array> tag:
<bean id="googleGeocodingService" class="geocoding.GoogleGeocodingService">
<constructor-arg ref="proxy" />
<constructor-arg value="" />
</bean>
<bean id="geocodingService" class="geocoding.RandomGeocodingService">
<constructor-arg>
<array value-type="geocoding.GeocodingService">
<!-- How do I reference the google geocoding service here? -->
</array>
</constructor-arg>
</bean>
I haven't been able to find an example or something in the in the documentation on how to do this. Also, you have any suggestions for a better way of acheiving what I'm trying to do, please let me know :).
That's because there's no such thing as <array>, there's only <list>.
The good news is that Spring will auto-convert between lists and arrays as required, so defined your array as a <list>, and Spring will be coerce it into an array for you.
This should work:
<bean id="googleGeocodingService" class="geocoding.GoogleGeocodingService">
<constructor-arg ref="proxy" />
<constructor-arg value="" />
</bean>
<bean id="geocodingService" class="geocoding.RandomGeocodingService">
<constructor-arg>
<list>
<ref bean="googleGeocodingService"/>
</list>
</constructor-arg>
</bean>
Spring will also coerce a single bean into a list, if required:
<bean id="geocodingService" class="geocoding.RandomGeocodingService">
<constructor-arg>
<ref bean="googleGeocodingService"/>
</constructor-arg>
</bean>
Spring can automatically convert a list into an array[]
check it out http://forum.springsource.org/showthread.php?37767-Injecting-String-Array
<bean name="test" class="Test">
<property name="values" value="hugo,emil"></property>
</bean>
Check out the util schema.
I'm actually using <array> tag to inject an array of objects into a bean and it works.
Take a look at the following code...
<bean id="song1" class="mx.com.company.songs.Song">
<property name="name" value="Have you ever seen the rain?"/>
</bean>
<bean id="song2" class="mx.com.company.songs.Song">
<property name="name" value="La bamba"/>
</bean>
<bean id="guitarPlayer" class="mx.com.company.musician.GuitarPlayer">
<property name="songs">
<array>
<ref bean="song1"/>
<ref bean="song2"/>
</array>
</property>
</bean>

Categories

Resources