Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring core. Default @Bean destroy method

I have my own bean:

@Bean public MyBean myBean(){... 

following spring documentation to release its own resources I should specify destroyMethod. I've not found any default destroy methods called by spring in case if destroyMethod is not specified directly.

I used

@Bean(destroyMethod = "close") public MyBean myBean(){... 

but think about possibility to do not specify destroy method directly if it has value by default.


Does spring try something by default like destroy, close, release? If spring tries some methods by default to release resources - which ones?

like image 623
Sergii Avatar asked Jun 26 '17 09:06

Sergii


People also ask

When Bean destroy-method is called?

display() as destroy-method is valued in the bean definition. The default scope with which bean is created is singleton hence, invoking the factory. destroySingletons() will call the method mentioned in the destroy-method . Follow this answer to receive notifications.

How can call destroy-method in Spring bean?

destroy-method is bean attribute using which we can assign a custom bean method that will be called just before the bean is destroyed. To use the destroy-method attribute, we do as follows. Here myPreDestroy() method will be defined in the Student class. Spring will call this method just before destroying the bean.

Can we use @bean without @configuration?

@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.

What is @configuration and @bean in Spring?

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.


1 Answers

As documented in Bean.destroyMethod:

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

In other words, if you don't specify destroyMethod, but the bean has a public close() or shutdown() method, it will be automatically used as the destroy-method.

To disable this inference, use @Bean(destroyMethod = "").

like image 54
Mark Rotteveel Avatar answered Oct 09 '22 11:10

Mark Rotteveel