Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

java - Optional Spring bean references

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...