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?
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.
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.
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.
If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With