溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用spring容器在初始化Bean時前和后的操作是怎樣的

發布時間:2021-09-24 14:54:32 來源:億速云 閱讀:191 作者:柒染 欄目:開發技術

本篇文章給大家分享的是有關使用spring容器在初始化Bean時前和后的操作是怎樣的,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧

spring容器初始化Bean操作

在某些情況下,Spring容器在初始化Bean的時候,希望在初始化bean前和銷毀bean前進行一些資源的加載和釋放的操作??梢酝ㄟ^一下三種方式完成。

  • Bean的方法加上@PostConstruct和@PreDestroy注解

  • 在xml中定義init-method和destory-method方法

  • Bean實現InitializingBean和DisposableBean接口

@PostConstruct和@PreDestroy注解

JavaBean代碼

@Component
public 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配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd        
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
    <!-- spring掃描的路徑 -->
    <context:component-scan base-package="spring.zhujie" />
</beans>

測試代碼和結果

測試代碼

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

運行結果

PersonService.class init method ...

PersonService.class cleanUp method ...

在XML中定義init-method和destory-method方法

JavaBean代碼

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配置文件

<bean class="spring.zhujie.PersonService" init-method="init" destroy-method="cleanUp"/>

測試代碼和結果

測試代碼

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

運行結果

PersonService.class init method ...

六月 23, 2017 9:42:06 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose

信息: 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實現InitializingBean和DisposableBean接口

JavaBean代碼

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配置文件

<bean id="personService" class="spring.zhujie.PersonService" />

測試代碼和結果

測試代碼

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

運行結果

PersonService.class init method ...

PersonService.class cleanUp method ...

Spring bean 初始化順序

InitializingBean, init-method 和 PostConstruct

1、概述

從接口的名字上不難發現,InitializingBean 的作用就是在 bean 初始化后執行定制化的操作。

Spring 容器中的 Bean 是有生命周期的,Spring 允許在 Bean 在初始化完成后以及 Bean 銷毀前執行特定的操作,常用的設定方式有以下三種:

通過實現 InitializingBean/DisposableBean 接口來定制初始化之后/銷毀之前的操作方法;

通過 <bean> 元素的 init-method/destroy-method 屬性指定初始化之后 /銷毀之前調用的操作方法;

在指定方法上加上@PostConstruct 或@PreDestroy注解來制定該方法是在初始化之后還是銷毀之前調用。

2、InitializingBean vs init-method

接口定義如下:

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

接口只有一個方法afterPropertiesSet,

此方法的調用入口是負責加載 spring bean 的AbstractAutowireCapableBeanFactory,源碼如下:

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 + "'");
   }
   //先調用afterPropertiesSet()進行初始化
   if (System.getSecurityManager() != null) {
    try {
     AccessController.doPrivileged(
       new PrivilegedExceptionAction(bean) {
        public Object run() throws Exception {
         ((InitializingBean) this.val$bean)
           .afterPropertiesSet();
         return null;
        }
       }, getAccessControlContext());
    } catch (PrivilegedActionException pae) {
     throw pae.getException();
    }
   } else {
    ((InitializingBean) bean).afterPropertiesSet();
   }
  }
  
  //然后調用InitMethod()進行初始化
  if (mbd != null) {
   String initMethodName = mbd.getInitMethodName();
   if ((initMethodName == null)
     || ((isInitializingBean) && ("afterPropertiesSet"
       .equals(initMethodName)))
     || (mbd.isExternallyManagedInitMethod(initMethodName)))
    return;
   invokeCustomInitMethod(beanName, bean, mbd);
  }
 }

從這段源碼可以得出以下結論:

spring為bean提供了兩種初始化bean的方式,實現InitializingBean接口,實現afterPropertiesSet方法,或者在配置文件中通過init-method指定,兩種方式可以同時使用

實現InitializingBean接口是直接調用afterPropertiesSet方法,比通過反射調用init-method指定的方法效率相對來說要高點。但是init-method方式消除了對spring的依賴

先調用afterPropertiesSet,再執行 init-method 方法,如果調用afterPropertiesSet方法時出錯,則不調用init-method指定的方法

3、@PostConstruct

通過 debug 和調用棧找到類InitDestroyAnnotationBeanPostProcessor, 其中的核心方法,即 @PostConstruct 方法調用的入口:

@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;
    }

從命名上,我們就可以得到某些信息——這是一個BeanPostProcessor。BeanPostProcessor的postProcessBeforeInitialization是在Bean生命周期中afterPropertiesSet和init-method之前被調用的。另外通過跟蹤,@PostConstruct方法的調用方式也是通過反射機制。

4、小結一下吧

spring bean的初始化執行順序:構造方法 --> @PostConstruct注解的方法 --> afterPropertiesSet方法 --> init-method指定的方法。具體可以參考例子

afterPropertiesSet通過接口實現方式調用(效率上高一點),@PostConstruct和init-method都是通過反射機制調用

同理,bean銷毀過程的順序為:@PreDestroy > DisposableBean > destroy-method

不再展開,看源碼就好

測試代碼如下:

@Slf4j
public 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");
    }
}
@Configuration
public class SystemConfig {
    @Bean(initMethod = "initMethod", name = "initSequenceBean")
    public InitSequenceBean initSequenceBean() {
        return new InitSequenceBean();
    }
}
@Slf4j
public class InitSequenceBeanTest extends ApplicationTests {
    @Autowired
    private InitSequenceBean initSequenceBean;
    @Test
    public void initSequenceBeanTest() {
        log.info("Finish: {}", initSequenceBean.toString());
    }
}

以上就是使用spring容器在初始化Bean時前和后的操作是怎樣的,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女