Get the App
SLTechnology News&Howtos  ›  Development  › 

Spring annotations how to specify InitMethod and DestroyMethod for bean

Shulou Source: shulou.com Published: 2022-06-02 13:30:37 09月23日 Update

This article mainly shows you "spring annotations how to specify InitMethod and DestroyMethod for bean", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "spring annotations how to specify InitMethod and DestroyMethod for bean" this article.

Spring comments specify InitMethod and DestroyMethod/** for bean to specify init methods and destroy methods for construction * 1: in the configuration class @ Bean (initMethod = "init", destroyMethod = "destory") note specifies * 2: implement the InitializingBean interface to override its afterPropertiesSet method and DisposableBean interface to rewrite the destroy method * 3: use @ PostConstruct in the JSR250 specification of java to mark the init method, and @ PreDestroy to mark the destroy note * /

It is important to note that:

Single instance bean: creates an object when the container starts

Multi-instance bean: create an object each time you get it

Initialize:

Object creation is complete, assignment is complete, initialization method is called

Destroy:

Single instance: called when the container is closed

Multiple instances: the container will not be destroyed and can only be called manually.

Here is the specific code

Car.java

Public class Car {public Car () {System.out.println ("Car's Constructor..");} public void init () {System.out.println ("Car's Init...");} public void destory () {System.out.println ("Car's Destroy...");}}

Configuration class

@ Bean (initMethod = "init", destroyMethod = "destory") public Car car () {return new Car ();} Note initMethod and destroyMethod@Configurationpublic class AppConfig {@ Bean (initMethod = "init") public Foo foo () {return new Foo ();} @ Bean (destroyMethod = "cleanup") public Bar bar () {return new Bar ();}

There are no parentheses after initMethod and destroyMethod in the above code.

Remember not to wear parentheses.

The above is all the content of the article "how to specify InitMethod and DestroyMethod for bean with spring comments". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Methods annotations examples content containers objects articles code parentheses interfaces learning help configuration manual tonal easy to understand more organization knowledge editing Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Docker Microsoft Redmi NVidia