Thursday, October 25, 2012

ref element

The ref element is the final element allowed inside a property definition element. It is used to set the value of the specified property to be a reference to another bean managed by the container, a collaborator, so to speak. As mentioned in a previous section, the referred-to bean is considered to be a dependency of the bean who's property is being set, and will be initialized on demand as needed (if it is a singleton bean it may have already been initialized by the container) before the property is set. All references are ultimately just a reference to another object, but there are 3 variations on how the id/name of the other object may be specified, which determines how scoping and validation is handled.





<ref bean="someBean"/>
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 local="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 parent="someBean"/>


Specifying the target bean by using the parent attribute allows a reference to be created to a bean which is in a parent BeanFactory (or ApplicationContext) of the current BeanFactory (or ApplicationContext). The value of the parent 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, and the target bean must be in a parent BeanFactory or ApplicationContext to the current one. The main use of this bean reference variant is when there is a need to wrap an existing bean in a parent context with some sort of proxy (which may have the same name as the parent), and needs the original object so it may wrap it.

No comments:

Post a Comment