Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Spring bean references

Tags:

In my application I am using ContextLoaderListener to load context files from many jars using:

<context-param>     <param-name>contextConfigLocation</param-name>     <param-value>classpath*:META-INF/contextBeans.xml</param-value> </context-param> 

This means I can reference beans from other jars without doing import.

In the application there are multiple deployment options and in some deployments jars can be excluded. To support that I would like some bean references to be optional. For example:

<bean id="mainAppBean" class="com.someapp.MyApplication">     <constructor-arg index="0" ref="localBean"/>      <constructor-arg index="1" ref="optionalBeanReference1"/>     <constructor-arg index="2" ref="optionalBeanReference2"/>  </bean> 

In the example above I would like to have optionalBeanReference1 equal null if the reference was not found (mark it optional in some way)

Can this be done in Spring? or what method do you recommend for handling dynamic references?

like image 722
mbdev Avatar asked Oct 18 '10 08:10

mbdev


People also ask

How do you reference a Spring bean?

If you are referring to a bean in different XML file, you can reference it with a ' ref ' tag, ' bean ' attribute. In this example, the bean “OutputHelper” declared in ' Spring-Common. xml ' can access to other beans in ' Spring-Output.

How do you get the BeanFactory reference in any class?

I can have my class implement BeanFactoryAware to get a reference to my beanfactory. Then I can do beanFactory. getBean("name"); to get access to a single bean.

What is BeanFactory?

The BeanFactory is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves.

How do you make auto writing as non mandatory for a specific bean property?

If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.


1 Answers

My best guess is to use autowire-ing with required false. Don't know how you can express this in XML but using annotation configuration this would look like:

@Autowired(required=false) 
like image 130
Cristian Vrabie Avatar answered Sep 17 '22 17:09

Cristian Vrabie