问题描述:

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.NoSuchBeanDefinitionException

网友答案:

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

相关阅读:
Top