《spring扩展点之二:spring中关于bean初始化、销毁等使用汇总,ApplicationContextAware将ApplicationContext注入》
《spring中InitializingBean接口使用理解》
关于在spring  容器初始化 bean 和销毁前所做的操作定义方式有三种:

第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作

第二种是:通过在xml中定义init-method 和destory-method方法

第三种是:通过bean实现InitializingBean和 DisposableBean接口

例如:TransactionTemplate实现InitializingBean接口,主要是判断transactionManager是否已经初始化,如果没有则抛出异常。源码如下:

public void afterPropertiesSet() {if (this.transactionManager == null) {throw new IllegalArgumentException("Property 'transactionManager' is required");}
}

目前我知道的有:在xml中定义的时候用init-method和destory-method,还有一种就是定义bean的时候实现DisposableBean和InitializingBean 这两个接口,打开InitializingBean 的源码:

public interface InitializingBean {/*** Invoked by a BeanFactory after it has set all bean properties supplied* (and satisfied BeanFactoryAware and ApplicationContextAware).* <p>This method allows the bean instance to perform initialization only* possible when all bean properties have been set and to throw an* exception in the event of misconfiguration.* @throws Exception in the event of misconfiguration (such* as failure to set an essential property) or if initialization fails.*/void afterPropertiesSet() throws Exception;}

根据注解很清楚的可以看出,afterPropertiesSet()表示在资源加载完以后,初始化bean之前执行的方法,我猜想spring底层应该会在初始化bean的时候,应该会使用(bean instanceof InitializingBean)判断是不是实现了这个接口,其实在很多框架中都是这么干的,但是因为没研究过spring源码,暂且还不知道底层原理。这样我们就可以在初始化的时候,做一些自己想要做的事了。
同理,DisposableBean就是在一个bean被销毁的时候,spring容器会帮你自动执行这个方法,估计底层原理也是差不多的,对于一些使用完之后需要释放资源的bean,我们都会实现这个接口,或者是配置destory-method方法。源码也基本是相似的,只是把afterPropertiesSet改为destroy。

public interface DisposableBean {/*** Invoked by a BeanFactory on destruction of a singleton.* @throws Exception in case of shutdown errors.* Exceptions will get logged but not rethrown to allow* other beans to release their resources too.*/void destroy() throws Exception;}

ApplicationContextAware
  其实我们看到---Aware就知道是干嘛用的了,就是属性注入的,但是这个ApplicationContextAware的不同地方在于,实现了这个接口的bean,当spring容器初始化的时候,会自动的将ApplicationContext注入进来:

import org.apache.commons.lang.Validate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
/*** applicationContext静态化* 使用了ApplicationContextAware接口的类,如果受spring容器管理的* 话,那么就会自动的调用ApplicationContextAware中的setApplicationContext方法* @author Hotusm**/
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware,DisposableBean{private static ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext)throws BeansException {SpringContextHolder.applicationContext=applicationContext;}//清空applicationContext 设置其为null
    @Overridepublic void destroy() throws Exception {SpringContextHolder.clearHolder();}//获得applicationContextpublic static ApplicationContext getApplicationContext() {//assertContextInjected();return applicationContext;}public static void clearHolder(){applicationContext=null;}//获取Beanpublic static <T> T getBean(Class<T> requiredType){//assertContextInjected();return (T) getApplicationContext().getBean(requiredType);}@SuppressWarnings("unchecked")public static <T> T getBean(String name){assertContextInjected();return (T) getApplicationContext().getBean(name);}//判断application是否为空public static void assertContextInjected(){Validate.isTrue(applicationContext==null, "application未注入 ,请在springContext.xml中注入SpringHolder!");}}

因为我们在做开发的时候,并不是说在每一个地方都能将属性注入到我们想要的地方去的,比如在Utils使用到dao,我们就不能直接注入了,这个时候就是我们需要封装springContext的时候了,而ApplicationContextAware就起了关键性的作用。

转载于:https://www.cnblogs.com/duanxz/p/4537195.html

spring扩展点之二:spring中关于bean初始化、销毁等使用汇总,ApplicationContextAware将ApplicationContext注入...相关推荐

  1. Spring学习笔记-Bean初始化销毁

    1.bean的初始化操作 1.1通过在配置文件中,设置bean的init-method方法,destory-method方法,spring框架会通过反射机制来调用 java类 package com. ...

  2. spring面试题(二)

    目录 硅谷 一 .请写出 spring 中常用的依赖注入方式. 二  .简述Spring中IOC容器常用的接口和具体的实现类 三 .简述Spring中如何基于注解配置Bean和装配Bean 四.  说 ...

  3. FastJson序列化Json自定义返回字段,普通类从spring容器中获取bean

    前言: 数据库的字段比如:price:1 ,返回需要price:1元. 这时两种途径修改: ① 比如sql中修改或者是在实体类转json前遍历修改. ②返回json,序列化时候修改.用到的是fastj ...

  4. Spring核心技术(七)——Spring容器的扩展

    本文将讨论如何关于在Spring生命周期中扩展Spring中的Bean功能. 容器的扩展 通常来说,开发者不需要通过继承ApplicationContext来实现自己的子类扩展功能.但是Spring ...

  5. Spring Framework 5.0.0.M4中文文档第3章

    文章目录 Part II. 核心技术 3. IoC容器 3.2 容器概述 3.2.1 配置元数据 3.2.2 实例化容器 3.2.3 使用容器 3.3 Bean概述 3.3.1 命名bean 3.3. ...

  6. Spring实战(三)Spring中装配Bean的三种方式---XML、JavaConfig、AutoWire

    创建应用对象之间协作关系的行为称为装配(wiring),这也是依赖注入的本质. Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系,而开发者需要告诉Spring需要创建哪些 ...

  7. springboot线程中获取bean

    在线程中是无法直接使用Spring Beans,但是又需要使用Spring中的bean执行方法 1:使用ApplicationContextAware在线程中直接获取bean 创建Applicatio ...

  8. spring_Spring MVC框架中的Bean作用域示例

    spring Spring框架或Spring MVC中的Bean作用域是由Spring IOC容器管理的Bean的作用域. 您可能知道Spring是一个基于依赖注入和控制反转的框架,并且为Java应用 ...

  9. spring boot高性能实现二维码扫码登录(中)——Redis版

    前言 本打算用CountDownLatch来实现,但有个问题我没有考虑,就是当用户APP没有扫二维码的时候,线程会阻塞5分钟,这反而造成性能的下降.好吧,现在回归传统方式:前端ajax每隔1秒或2秒发 ...

最新文章

  1. awk,sed,grep基本用法列举
  2. IBM收购Q1 Labs
  3. python中cumsum_在python里“np.cumsum”这个命令是干什么的?怎么使用?
  4. C语言 数组排序 – 插入法排序 - C语言零基础入门教程
  5. 【程序设计】浅析编程语言的区间为何常是左闭右开
  6. [转]我的数据结构不可能这么可爱!——珂朵莉树(ODT)详解
  7. Linux中使用Vim快速更换文档中Windows换行符为Linux平台
  8. SQL Server 填充因子
  9. Intel SGX技术详细解释(非常棒)
  10. 探索实践之软件构建(一)
  11. .net Core 3.1 项目打包部署到Windows服务
  12. js 经纬度坐标转换
  13. 【锂知道】锂电池基本原理解析:充电及放电机制
  14. 计算系数(多项式展开+快速幂)
  15. 怎么创建自己的网站?创建自己网站的步骤
  16. Excel DATEDIF函数
  17. 不是所有数学命题都是可以被证明或证伪
  18. 传音控股再度携手联合国难民署 驰援非洲儿童教育事业
  19. Shell脚本攻略04-玩转文件描述符及重定向
  20. excel隐藏的选项卡和命令栏怎么找回?

热门文章

  1. python求50的阶乘_python如何求阶乘
  2. ionic4 ts跳转传值 this.navController.navigateForward
  3. 编码器 stm32_STM32榨干编码旋钮(第一期)
  4. oracle 循环修改数据库,oracle对一个表的多行数据进行修改,SQL批量修改
  5. xml getelementsbytagname php,用PHP编写和读取XML的几种方式
  6. c语言lua读文件,file-io – 在Lua中逐行读取文件
  7. python添加自定义模块_Python中添加自定义模块的方法
  8. 下载的长数据怎么分开R语言_R语言学习笔记(一):学代码,我们从最基础的开始...
  9. slot多作用域 vue_vue插槽
  10. oracle 添加默认值列,Oracle 11g增加列,并带默认值的新特性