Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the custom initialization and destruction method of Bean

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge of what Bean custom initialization and destruction methods are. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

Bean three kinds of custom initialization and destruction. Overview of three methods

Specify @ Bean (initMethod = "init", destroyMethod = "destory") annotation in the configuration class

Implement InitializingBean interface and override its afterPropertiesSet method, implement DisposableBean interface and override destroy method

Use @ PostConstruct in java's JSR250 specification to mark on the init method, and @ PreDestroy on the destroy method

two。 Detailed description of methods

1. Method 1: specify in the configuration class

Sample code

Public class CarA {public CarA () {System.out.println ("CarA. Constructor ");} public void initCarA () {System.out.println (" init () method of CarA ");} public void destroyCarA () {System.out.println (" destroy () method of CarA ");}} @ Configurationpublic class ConfigTest {@ Bean (initMethod =" initCarA ", destroyMethod =" destroyCarA ") public CarA carA () {return new CarA ();}}

Execution result

CarA . Constructor function

The init () method of CarA

Service start

The destroy () method of CarA

two。 Method 2: implement the interface and rewrite the method

2.1 sample code

Public class CarB implements InitializingBean, DisposableBean {public CarB () {System.out.println ("CarB. Constructor ");} @ Override public void afterPropertiesSet () throws Exception {System.out.println (" CarB. The afterPropertiesSet () method executes ");} @ Override public void destroy () throws Exception {System.out.println (" CarB. Destroy () method executes ");} @ Configurationpublic class ConfigTest {@ Bean public CarB carB () {return new CarB ();}}

Execution result

CarB . Constructor function

CarB . AfterPropertiesSet () method execution

Service start

CarB . Destroy () method execution

2.2 Overview

Spring opens an extension interface that allows us to customize the initialization and destruction methods of bean. That is, when the Spring container reaches the corresponding lifecycle stage in bean, it will automatically call our custom initialization and destruction methods. The two extension interfaces are InitializingBean and DisposableBean.

InitializingBean API description: this API provides bean with the processing method after bean attribute initialization. It has only afterPropertiesSet method. All classes that implement this interface will execute this method after bean attribute initialization.

Package org.springframework.beans.factory

Public interface InitializingBean {void afterPropertiesSet () throws Exception;}

DisposableBean API description: this API provides a processing method for a singleton bean when the container terminates the bean. It has only destroy method. All classes that implement this API will execute this method when the bean is terminated.

Package org.springframework.beans.factory;public interface DisposableBean {void destroy () throws Exception;}

2.3 method 1 & & method 2

The same point: these are initialization methods that need to be executed after the bean property is initialized.

Differences

Method 1: code is not coupled to Spring; execution efficiency is low (initMethod method is executed through reflection)

Method 2: code is tightly coupled to Spring; faster (cast bean to InitializingBean interface type, and then call the afterPropertiesSet method directly)

Note: afterPropertiesSet and initMethod can exist at the same time, but the afterPropertiesSet method is executed before the initMethod method.

A summary of the process from creation to initialization of bean

Create a bean through a constructor

Attribute injection

Execute the afterPropertiesSet method

Execute the initMethod method

3. Method 3: using java's JSR250 specification

Code example

Public class CarC {public CarC () {System.out.println ("CarC. Constructor ");} @ PostConstruct public void initCarC () {System.out.println (" CarC. Initialize the method initCarC () ");} @ PreDestroy public void destroyCarC () {System.out.println (" CarC. Destroy method destroyCarC ");} @ Configurationpublic class ConfigTest {@ Bean public CarC carC () {return new CarC ();}}

Execution result

CarC . Constructor function

CarC . Initialization method initCarC ()

Service start

CarC . Destroy method destroyCarC

Get custom annotation Bean after spring initialization

The purpose is to associate the information of a specific class (such as the interface number) with the class through annotations, and then obtain the corresponding bean through the interface number to execute the corresponding logic.

one。 Create a new annotation class @ Target ({ElementType.METHOD, ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Servicepublic @ interface ServiceCode {String code () default "; String className () default";}

Contains the interface number and beanName information.

two。 Create a new interface class @ ServiceCode (code = "100010", className = "echoService") @ Service ("echoService") public class EchoService {} 3. Implement interface ApplicationListener

To listen to the execution after initialization of the spring container:

@ Component@Order (1) public class ServiceInitListener implements ApplicationListener {private static final Logger LOGGER = LoggerFactory.getLogger (ServiceInitListener.class); @ Override public void onApplicationEvent (ContextRefreshedEvent event) {ApplicationContext applicationContext = event.getApplicationContext () / / Note that the bean can only be obtained from the root container through annotations when needed. For example, only some public registrations bean if (applicationContext.getParent ()! = null) {applicationContext = applicationContext.getParent ();} Map beansWithAnnotation = applicationContext.getBeansWithAnnotation (ServiceCode.class) are found in the containers directly obtained by event. For (Object bean: beansWithAnnotation.values ()) {ServiceCode annotation = bean.getClass () .getAnnotation (ServiceCode.class); String code = annotation.code (); String className = annotation.className () / / Register the interface number and beanName / / you can obtain the beanName through code at the unified entry, and then obtain the corresponding bean via springContext to execute custom logic / / or complete other logic}

Note:

The context obtained by ContextRefreshedEvent is not the root spring container, and only part of the spring has built-in bean. The custom bean cannot be obtained through annotations. You need to obtain its parent container to complete the operation. The first time I got the beanList, it was always empty. Later, I found that the internal bean of the container did not have a custom service bean. After getting the parent container, everything was fine.

The @ Order annotation is used to customize the execution order, and the smaller the execution is, the more priority it is.

These are all the contents of this article entitled "what is the custom initialization and destruction method of Bean". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report