Setting `destroyMethod` on beans returning types with `close()` or `shutdown()` method

Viewed 1135

I am not sure how to understand the documentation for destroyMethod method of Bean type.

It says:

As a convenience to the user, the container will attempt to infer a destroy method against an object returned from the @Bean method. For example, given an @Bean method returning an Apache Commons DBCP BasicDataSource, the container will notice the close() method available on that object and automatically register it as the destroyMethod. This 'destroy method inference' is currently limited to detecting only public, no-arg methods named 'close' or 'shutdown'.

Does it mean that the Bean({destroyMethod="close"}) is redundant on types having close() method and Bean({destroyMethod="shutdown"}) on types having shutdown() method, as they will always be inferred automatically?

If that's the case it seeems that usage of destroyMethod="close" or destroyMethod="shutdown" is redundant in all cases. Am I right?

1 Answers

You are exactly right and have understood the docs correctly! If you'd like to see proof, take a look at the DisposableBeanAdapter:

private static final String CLOSE_METHOD_NAME = "close";

private static final String SHUTDOWN_METHOD_NAME = "shutdown";

and the #hasDestroyMethod:

public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {
        ...
        if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName)) {
            return (ClassUtils.hasMethod(bean.getClass(), CLOSE_METHOD_NAME) ||
                    ClassUtils.hasMethod(bean.getClass(), SHUTDOWN_METHOD_NAME));
        }
        ...
    }

You can browse around that area of the framework if you're interested.

Related