JBoss.org Community Documentation

12.3. Service dependencies

So far we have considered how POJOs depend on each other either explictly through injections or implicitly through the use of arbitrary objects supplied during deployment. These dependencies help us to assemble POJOs in a well defined order to create services but what about when one service depends on another?

Services typically consist of many individual POJOs wired together in order to perform a well-defined function. Once a service is deployed it can be stopped and started as many times as necessary in order to make best use of valuable resources such as CPU and memory. This is possible thanks to the service lifecycle:

  • create - the service has been deployed

  • start - the service is started

  • stop - the service is stopped

  • destroy - the service is being undeployed

If one service depends on another then we need someway to ensure that they are created and started in the correct order. Similarly we also need to ensure that they are stopped and destroyed correctly. This is done by adding a @Depends annotation or <depends> element to the POJO that defines a service's public methods and specifying the name of the bean that represents the other service.


@Depends("AnotherBean")
public class MyBean {
    ...
}

<bean name="AnotherBean" class="org.jboss.test.Example"/>

<bean name="MyBean" class="org.jboss.test.Example">
    <depends>AnotherBean</depends>
</bean>

The microcontainer will then ensure that the beans, representing the two services, are deployed in the correct order. Specifically the beans named in the @Depends or <depends> values will reach their CREATE states before the bean declaring the dependencies reaches its CREATE state. The same is true for the START, STOP and DESTROY states. It's possible to define multiple dependencies on other services simply by listing names or nesting <depends> elements:


@Depends("AnotherBean", "YetAnotherBean")
public class MyBean {
    ...
}

<bean name="AnotherBean" class="org.jboss.test.Example"/>

<bean name="MyBean" class="org.jboss.test.Example">
    <depends>AnotherBean</depends>
    <depends>YetAnotherBean</depends>
</bean>