When to use <ref bean> and when to use <ref local> in Spring? - spring

When to use <ref bean="service" /> and when to use <ref local="service" /> in Spring?

Specifying the target bean by using the bean attribute of the ref tag is the most general form, and will allow creating a reference to any bean in the same BeanFactory/ApplicationContext (whether or not in the same XML file), or parent BeanFactory/ApplicationContext. The value of the bean attribute may be the same as either the id attribute of the target bean, or one of the values in the name attribute of the target bean.
<ref bean="someBean"/>
Specifying the target bean by using the local attribute leverages the ability of the XML parser to validate XML id references within the same file. The value of the local attribute must be the same as the id attribute of the target bean. The XML parser will issue an error if no matching element is found in the same file. As such, using the local variant is the best choice (in order to know about errors are early as possible) if the target bean is in the same XML file.
<ref local="someBean"/>
This is from the Spring source reference here

The local attribute on the ref element is no longer supported in the 4.0 beans xsd since it does not provide value over a regular bean reference anymore. Simply change your existing ref local references to ref bean when upgrading to the 4.0 schema.

<ref local="someBeanId"> should be used when you have a duplicate id in your parent-child config files and you want to distinguish between the two in either config file.
<ref parent="someBeanId"> should be used in the child config file to reference the parent id.
<ref bean="someBeanId"> should be used when you do not have a duplicate id in your parent-child config files.

<ref local=".."> requires that the bean being referenced is in the same config file.
<ref bean="..."> requires only it to be in the same context, or in a parent context.
The difference is primarily one of documentation. If you see <ref local="...">, then you know you need only look in the same file to find it. Other than that, there's not much difference. I would generally use <ref bean="..."> in most cases.

In spring 4.1
the local attribute is not valid.
i used in the parent xml a name attribute for the
and in the child file a referenced the bean by the alias i gave already.

Related

how to control the sequence of object creation in spring?

in xml based approach, we configure the bean definition in xml ,
beans will be created in the order we have defined the beans.
1) <beans>
<bean id="a" class="com.abc.a"/>
`<bean id="b" class="com.abc.b"/>`
</beans>
Here , a will be created first before b.
2)<beans>
<bean id="a" class="com.abc.a">
<property name="c" ref="c"/>
</bean>
<bean id="b" class="com.abc.b/">
<bean id="c" class="com.abc.c/">
here c will be created first, then a then b.
In case of annotation driven approach, how to control the sequence of object creation? using ordered interface ?
Spring container creates the dependent objects (because they are needed by the main objects as per the object graph) first both in xml & annotation approach.
In case of annotation driven approach, how to control the sequence of object creation? using ordered interface ?
You can't control the order of objects as the dependent objects are always needed to be created first and then followed by the main objects.
The order interface is for a different purpose which is to push the objects into a list using autowired.
You can refer the example in the below link for using #Order to set/push an object into a list:
What is the use of #Order annotation in Spring?
Spring has an Order attribute of java config and an order attribute for xml configuration to control the order in which beans are created. (Lower values means earlyer creation, negative number are allowed too)
An other way is to control the order is DependsOn annotation/attribute.

How to iterate over a property file in Spring xml

I have a property file Details2.txt and it is filled with some values like :
list.value=34
list.value=35
list.value=38
list.value=45
list.value=23
Now i want to iterate this in my spring xml and i am unable to do so
XML code (parts only) :
<context:property-placeholder location="Details2.txt" />
<constructor-arg>
<list>
<value>${list.value}</value>
</list>
</constructor-arg>
this gives only the last value in property file
A property file will be translated to a Properties object, which in turn is a subclass of Hashtable, which contains a one-to-one mapping from key to value. This means that the Properties object will indeed only contain the last value (since the previous ones will have been overwritten).
One common way of handing this problem in property files is to add a suffix to the keys:
list.value.1=34
list.value.2=35
list.value.3=36
list.value.4=37
but that doesn't help you when using Spring, since each property key will need to be explicitly specified in the XML file (and I'm assuming you don't know the exact number of items).
Your best bet would be to specify the items as a comma-separated list:
list.values=34,35,36,37
And then use a configuration trick, such as described here or here.

Reading property file in java using Spring

Have been trying to understand how to load a property file using Spring in java and populate java.util.Properties object.
Use this newly created property object as a constructor arguement for another bean.
Appreciate any pointers on this.
Thanks,
cabear
To load a properties file in Spring use the PropertiesFactoryBean to make it easier to use there is a properties tag in the util namespace you can use.
<util:properties id="props" location="location-of.properties" />
Then you have a bean named props which you can use as any regular bean.
<bean id="otherBean" class="my.app.MyClass" >
<constructor-arg ref="props" />
</bean>
When also using the property placeholder support you could use the same properties object again instead of loading it again, by referencing it using the properties-ref attribute of the property-placeholder tag.
<context:property-placeholder properties-ref="props" />
Here is how you read a properties file :
#Value("${memberaddedsubject}") // id of the content you want to read.
private String memberAddedSubject; // Taking content in String class.
To use this property file, you have to instruct spring, this way :
<util:properties id="props" location="your-location-to-props" />
Add the above line in your applicationContext.xml or the XML file you have(not web.xml)
I have put my properties file in /projectname/resources/.
I hope this is what you are looking for, if not, let me know.

Dynamically configuring java beans based on property file in Spring

Wondering if there is a way to dynamically instantiate beans based on set of values in your property file using PropertyPlaceholderConfigurer class.
I have a java bean say Student with two attributes: "name" and "subject"
I have a property file with:
student.1.name=student1name
student.1.subject=student1subject
student.2.name=student2name
student.2.name=student2subject
Now I have a Classroom object that can take a list of students.
I am wondering if there is a way we could do this using Spring. The challenge here is that the number of students could vary.
If there was only one student object then:
<bean id="student" class="com.abc.Student">
<property name="name" value="${student.1.name}" />
<property name="subject"
value="${student.1.subject}" />
</bean>
<bean id="classRoom" class="com.abc.ClassRoom">
<property name="student" ref="student" />
</bean>
would have worked. But in this case we have a list of n Students. And the value of n could vary depending on the number of entries in the properties file.
I'm with Kevin--IMO you're going about this the wrong way.
One possible workaround would be to create a bean that takes the property file as an argument, reads it in, and exposes a list of students (which would need to be indexed on something, like the n in the existing property file).
The classroom bean could then use that list of students.
But it sure looks like you're trying to duplicate the functionality of a DB, without a DB, in an awkward way.
I don't think there's a way to do that with PropertyPlaceholderConfigurer. Usually when I have a situation like that I choose a configuration format of either JSON or XML and use GSON/Jackson/JAXB to unmarshall the data into objects.

Can I use a property placeholder with Spring EL?

Before upgrading to Spring 3 I had this in my applicationContext.xml file:
<bean class="com.northgateis.pole.ws.PolePayloadValidatingInterceptor">
<property name="validateRequest" value="${validateRequest}" />
<property name="validateResponse" value="${validateResponse}" />
</bean>
where ${validateRequest) and ${validateRequest) refer to properties that may or may not be defined in my properties file.
In Spring 2, if these proeprties were not present in the properties file the setters on the bean were not called and so the defaults hard-coded in PolePayloadValidatingInterceptor were used.
After upgrading to Spring 3, it seems the behaviour is different: If the properties are not present in the properties file I get the following exception:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'annotationMapping' defined in class path resource [com/northgateis/pole/ws/applicationContext-ws.xml]: Could not resolve placeholder 'validateRequest'
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:272)
at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:75)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:640)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:615)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:405)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:272)
I tried dabbling with Spring EL but the following doesn't seem to work:
<bean class="com.northgateis.pole.ws.PolePayloadValidatingInterceptor">
<property name="validateRequest" value="${validateRequest?:true}" />
<property name="validateResponse" value="${validateResponse?:false}" />
</bean>
The value after the Elvis operator is always used, even when the properties are defined in the proeprties file. Interesting that the syntax is accepted.
Any suggestions?
It looks like Spring 3's handling of default values with the Elvis operator was rather broken. This has apparently been fixed (see SPR-7209) in the fresh-out-of-the-oven Spring 3.0.3, and the correct syntax should be the rather baroque:
#{${validateRequest}?:true}
There's no need for Spring EL for setting a default value for a missing property when resolving it with a placeholder configurer. Simply use ${validateRequest:true}. The "Elvis operator" is not concerned with resolving placeholders, it just relies on whatever input the placeholder configurer provides.
See SPR-4785.

Resources