开发者

Spring:define bean's property(ref to other bean) as optional

Have two bean definitions:

file a.xml

<bean id="A" class="com.A">
 <property name="bClass" ref="B"/>
</bean>

file b.xml

<bean id="B" class="com.B"/>

In some cases file b.xml does not contain definition of bean B.

And from other side,file a.xml always contains link to B definition.

How to define reference to B bean to be optional, in order to avoid org.springframework.beans.factory.NoSuchBea开发者_JAVA技巧nDefinitionException


You can't. If you have a reference to B, then B must exist. You need to ensure that some kind of stub B exists, the definition of which would be overridden by the definition of B in b.xml.

Alternatively, don't inject B into A, but make A look up B using BeanFactory.getBean("B"), and handle the potential absence of B programmatically.


Yet another possibility (on top of these suggested by skaffman) is to reverse the depenency. Let the bean B know the bean A. It can even register itself within it - that is, call the setter, e.g.:

public class B {
  private A a;

  public void init() {
    a.setB(this);
  }
}


@Autowired(required=false) helped

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜