Articles

Hooks into the bean lifecycle in the Ding container


Introduction

Sometimes it's useful (or needed) to have the container call certain methods right before injecting (or giving away) our beans, and right before destructing it, as a way of setup-teardown or init-shutdown.

Ding provides a way to execute code in some of the points of the bean lifecycle:

  • After the bean has been assembled, and all its dependencies injected.
  • Right before calling the bean's destructor.

We'll see how to use them with the 3 drivers. In the following examples, the method "init" will be called as soon as the beans are completely assembled, and the shutdown method will be called when the container is destroyed:

The annotations way

You can do this in 2 ways. At the method level:

/**
 * @Component
 */
class MyBean
{
    /** @PostConstruct */
    public function init()
    {
    }

    /** @PreDestroy */
    public function shutdown()
    {
    }
}

And at the class level:

/**
 * @Component
 * @InitMethod(method="init")
 * @DestroyMethod(method="shutdown")
 */
class MyBean
{
    public function init()
    {
    }

    public function shutdown()
    {
    }
}

The Xml way

<?xml version="1.0" encoding="UTF-8"?>
<beans>
  <bean id="myXmlBean"
    class="MyBean"
    init-method="init"
    destroy-method="shutdown"/>
</beans>

The Yaml way

beans:
  myYamlBean:
    class: MyBean
    init-method: init
    destroy-method: destroy