Question

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

Was it helpful?

Solution 3

@Autowired(required=false) helped

OTHER TIPS

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);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top