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 happens before and after initializing Bean using the spring container

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

Share

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

This article is about how to use the spring container before and after initializing Bean. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Without saying much, let's take a look at it with the editor.

The spring container initializes the Bean operation

In some cases, when initializing the Bean, the Spring container wants to load and release some resources before initializing the bean and before destroying the bean. It can be done in three ways.

Bean's method with @ PostConstruct and @ PreDestroy annotations

Define init-method and destory-method methods in xml

Bean implements the interface between InitializingBean and DisposableBean

@ PostConstruct and @ PreDestroy annotations

JavaBean code

@ Componentpublic class PersonService {private String message; public String getMessage () {return message;} public void setMessage (String message) {this.message = message;} @ PostConstruct public void init () {System.out.println ("PersonService.class init method...");} @ PreDestroy public void cleanUp () {System.out.println ("PersonService.class cleanUp method...");}}

Spring profile

Test code and results

Test code

Public static void main (String [] args) {AbstractApplicationContext context = new ClassPathXmlApplicationContext ("spring-zhujie.xml"); context.registerShutdownHook ();}

Running result

PersonService.class init method...

PersonService.class cleanUp method...

Define init-method and destory-method methods in XML

JavaBean code

Public class PersonService {private String message; public String getMessage () {return message;} public void setMessage (String message) {this.message = message;} public void init () {System.out.println ("PersonService.class init method...");} public void cleanUp () {System.out.println ("PersonService.class cleanUp method...");}}

Spring profile

Test code and results

Test code

Public static void main (String [] args) {AbstractApplicationContext context = new ClassPathXmlApplicationContext ("spring-xml.xml"); context.registerShutdownHook ();}

Running result

PersonService.class init method...

June 23, 2017 9:42:06 afternoon org.springframework.context.support.ClassPathXmlApplicationContext doClose

Information: Closing org.springframework.context.support.ClassPathXmlApplicationContext@7a94c5e7: startup date [Fri Jun 23 21:42:06 CST 2017]; root of context hierarchy

PersonService.class cleanUp method...

Bean implements the interface between InitializingBean and DisposableBean

JavaBean code

Public class PersonService implements InitializingBean, DisposableBean {private String message; public String getMessage () {return message;} public void setMessage (String message) {this.message = message;} @ Override public void afterPropertiesSet () throws Exception {System.out.println ("PersonService.class init method...");} @ Override public void destroy () throws Exception {System.out.println ("PersonService.class cleanUp method...") }}

Spring profile

Test code and results

Test code

Public static void main (String [] args) {AbstractApplicationContext context = new ClassPathXmlApplicationContext ("spring-interface.xml"); context.registerShutdownHook ();}

Running result

PersonService.class init method...

PersonService.class cleanUp method...

Spring bean initialization order

InitializingBean, init-method and PostConstruct

1. Overview

It is not difficult to see from the name of the interface that the purpose of InitializingBean is to perform customized operations after bean initialization.

The Bean in the Spring container has a lifecycle. Spring allows specific operations to be performed after the initialization of the Bean and before the destruction of the Bean. There are three common settings:

Customize the operation method after initialization / before destruction by implementing the InitializingBean/DisposableBean interface

Specify the action method called after initialization / before destruction through the init-method/destroy-method attribute of the element

Annotate the specified method with @ PostConstruct or @ PreDestroy to determine whether the method is called after initialization or before destruction.

2 、 InitializingBean vs init-method

The API is defined as follows:

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

There is only one method afterPropertiesSet for the interface

The call entry for this method is the AbstractAutowireCapableBeanFactory responsible for loading spring bean. The source code is as follows:

Protected void invokeInitMethods (String beanName, Object bean, RootBeanDefinition mbd) throws Throwable {boolean isInitializingBean = bean instanceof InitializingBean; if ((isInitializingBean) & & ((mbd = = null) | (!) (mbd .isExternallyManagedInitMethod ("afterPropertiesSet") {if (this.logger.isDebugEnabled ()) {this.logger .debug ("Invoking afterPropertiesSet () on bean with name'" + beanName + ")) } / / first call afterPropertiesSet () to initialize if (System.getSecurityManager ()! = null) {try {AccessController.doPrivileged (new PrivilegedExceptionAction (bean) {public Object run () throws Exception {((InitializingBean) this.val$bean) .initialPropertiesSet (); return null;}}, getAccessControlContext ());} catch (PrivilegedActionException pae) {throw pae.getException () }} else {((InitializingBean) bean) .afterPropertiesSet ();}} / then call InitMethod () to initialize if (mbd! = null) {String initMethodName = mbd.getInitMethodName (); if ((initMethodName = = null) | | (isInitializingBean) & & ("afterPropertiesSet" .equals (initMethodName)) | | (mbd.isExternallyManagedInitMethod (initMethodName)) return; invokeCustomInitMethod (beanName, bean, mbd);}}

The following conclusions can be drawn from this source code:

Spring provides bean with two ways to initialize bean, implement the InitializingBean interface, implement the afterPropertiesSet method, or specify it through init-method in the configuration file, both of which can be used at the same time

Implementing the InitializingBean interface calls the afterPropertiesSet method directly, which is relatively more efficient than calling the method specified by init-method through reflection. But the init-method approach eliminates the dependence on spring

First call afterPropertiesSet, then execute the init-method method. If there is an error in calling the afterPropertiesSet method, the method specified by init-method will not be called.

3. @ PostConstruct

Find the class InitDestroyAnnotationBeanPostProcessor through debug and call stack, the core method of which is the entry of the @ PostConstruct method call:

Override public Object postProcessBeforeInitialization (Object bean, String beanName) throws BeansException {LifecycleMetadata metadata = findLifecycleMetadata (bean.getClass ()); try {metadata.invokeInitMethods (bean, beanName);} catch (InvocationTargetException ex) {throw new BeanCreationException (beanName, "Invocation of init method failed", ex.getTargetException ()) } catch (Throwable ex) {throw new BeanCreationException (beanName, "Failed to invoke init method", ex);} return bean;}

From naming, we can get some information-- this is a BeanPostProcessor. BeanPostProcessor's postProcessBeforeInitialization is called before afterPropertiesSet and init-method in the Bean life cycle. In addition, through tracing, the @ PostConstruct method is also called through the reflection mechanism.

4. Make a summary.

The initialization order of spring bean: constructor-- > @ PostConstruct annotated method-- > afterPropertiesSet method-- > method specified by init-method. You can refer to examples for details.

AfterPropertiesSet is called through the interface (a little more efficient), and @ PostConstruct and init-method are called through the reflection mechanism.

Similarly, the order of bean destruction process is @ PreDestroy > DisposableBean > destroy-method

No longer expand, just look at the source code

The test code is as follows:

@ Slf4jpublic class InitSequenceBean implements InitializingBean {public InitSequenceBean () {log.info ("InitSequenceBean: construct");} @ Override public void afterPropertiesSet () throws Exception {log.info ("InitSequenceBean: afterPropertiesSet");} @ PostConstruct public void postConstruct () {log.info ("InitSequenceBean: postConstruct");} public void initMethod () {log.info ("InitSequenceBean: initMethod") } @ Configurationpublic class SystemConfig {@ Bean (initMethod = "initMethod", name = "initSequenceBean") public InitSequenceBean initSequenceBean () {return new InitSequenceBean ();} @ Slf4jpublic class InitSequenceBeanTest extends ApplicationTests {@ Autowired private InitSequenceBean initSequenceBean; @ Test public void initSequenceBeanTest () {log.info ("Finish: {}", initSequenceBean.toString ()) }} the above is what happens before and after using the spring container to initialize Bean. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow 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