spring的InitializingBean的 afterPropertiesSet 方法 和 init-method配置的区别联系
InitializingBean
Spirng的InitializingBean为bean提供了定义初始化方法的方式。InitializingBean是一个接口,它仅仅包含一个方法:afterPropertiesSet()。
Bean实现这个接口,在afterPropertiesSet()中编写初始化代码:
package research.spring.beanfactory.ch4; import org.springframework.beans.factory.InitializingBean; class LifeCycleBean implements InitializingBean{ void afterPropertiesSet() throws Exception { System. out .println("LifeCycleBean initializing..."); } }
在xml配置文件中并不需要对bean进行特殊的配置:
xml version="1.0" encoding="UTF-8" ?> DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
< bean name ="lifeBean" class ="research.spring.beanfactory.ch4.LifeCycleBean">
>
< /beans >
编写测试程序进行测试:
package research.spring.beanfactory.ch4; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class LifeCycleTest { static void main(String[] args) { XmlBeanFactory factory= new XmlBeanFactory( new ClassPathResource("research/spring/beanfactory/ch4/context.xml")); factory.getBean("lifeBean"); } }
运行上面的程序我们会看到:“LifeCycleBean initializing...”,这说明bean的afterPropertiesSet已经被Spring调用了。
Spring在设置完一个bean所有的合作者后,会检查bean是否实现了InitializingBean接口,如果实现就调用bean的afterPropertiesSet方法。
SHAPE /* MERGEFORMAT
|
装配 bean的合作者 |
|
查看 bean是否实现 InitializingBean 接口 |
|
调用 afterPropertiesSet 方法 |
Spring虽然可以通过InitializingBean完成一个bean初始化后对这个bean的回调,但是这种方式要求bean实现 InitializingBean接口。一但bean实现了InitializingBean接口,那么这个bean的代码就和Spring耦合到一起了。通常情况下我不鼓励bean直接实现InitializingBean,可以使用Spring提供的init-method的功能来执行一个bean 子定义的初始化方法。
写一个java class,这个类不实现任何Spring的接口。定义一个没有参数的方法init()。
package research.spring.beanfactory.ch4;
publicclass LifeCycleBean{
publicvoid init(){
System. out .println("LifeCycleBean.init...");
}
}
在Spring中配置这个bean:
xml version="1.0" encoding="UTF-8" ?> DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd" >< beans >< bean name ="lifeBean" class ="research.spring.beanfactory.ch4.LifeCycleBean"
init-method ="init"> bean > beans >
当Spring实例化lifeBean时,你会在控制台上看到” LifeCycleBean.init...”。
Spring要求init-method是一个无参数的方法,如果init-method指定的方法中有参数,那么Spring将会抛出 java.lang.NoSuchMethodException
init-method指定的方法可以是public、protected以及private的,并且方法也可以是final的。
init-method指定的方法可以是声明为抛出异常的,就像这样:
final protected void init() throws Exception{
System.out.println("init method...");
if(true) throw new Exception("init exception");
}
如果在init-method方法中抛出了异常,那么Spring将中止这个Bean的后续处理,并且抛出一个 org.springframework.beans.factory.BeanCreationException异常。
InitializingBean和init-method可以一起使用,Spring会先处理InitializingBean再处理init-method。
org.springframework.beans.factory.support. AbstractAutowireCapableBeanFactory完成一个Bean初始化方法的调用工作。 AbstractAutowireCapableBeanFactory是XmlBeanFactory的超类,再 AbstractAutowireCapableBeanFactory的invokeInitMethods方法中实现调用一个Bean初始化方法:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java:
// ……
//在一个bean的合作者设备完成后,执行一个bean的初始化方法。 protected void invokeInitMethods(String beanName, Object bean, RootBeanDefinition mergedBeanDefinition)
throws Throwable {
// 判断bean是否实现了InitializingBean接口 if (bean instanceof InitializingBean) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '"+ beanName +"'");
}
// 调用afterPropertiesSet方法
((InitializingBean) bean).afterPropertiesSet();
}
// 判断bean是否定义了init-method if (mergedBeanDefinition!= null &&mergedBeanDefinition.getInitMethodName() != null ) {
//调用invokeCustomInitMethod方法来执行init-method定义的方法
invokeCustomInitMethod(beanName, bean, mergedBeanDefinition.getInitMethodName());
} }
// 执行一个bean定义的init-method方法 protected void invokeCustomInitMethod(String beanName, Object bean, String initMethodName)
throws Throwable {
if (logger.isDebugEnabled()) {
logger.debug("Invoking custom init method '"+ initMethodName +"' on bean with name '"+ beanName +"'");
}
// 使用方法名,反射Method对象
Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null );
if (initMethod ==null) {
thrownew NoSuchMethodException(
"Couldn't find an init method named '"+ initMethodName +"' on bean with name '"+ beanName +"'");
}
// 判断方法是否是public if (!Modifier.isPublic(initMethod.getModifiers())) {
//设置accessible为true,可以访问private方法。 initMethod.setAccessible( true );
}
try {
//反射执行这个方法
initMethod.invoke(bean, (Object[]) null );
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
} }
// ………..
通过分析上面的源代码我们可以看到,init-method是通过反射执行的,而afterPropertiesSet是直接执行的。所以 afterPropertiesSet的执行效率比init-method要高,不过init-method消除了bean对Spring依赖。在实际使用时我推荐使用init-method。
需要注意的是Spring总是先处理bean定义的InitializingBean,然后才处理init-method。如果在Spirng处理InitializingBean时出错,那么Spring将直接抛出异常,不会再继续处理init-method。
如果一个bean被定义为非单例的,那么afterPropertiesSet和init-method在bean的每一个实例被创建时都会执行。单例 bean的afterPropertiesSet和init-method只在bean第一次被实例时调用一次。大多数情况下 afterPropertiesSet和init-method都应用在单例的bean上。
spring的InitializingBean的 afterPropertiesSet 方法 和 init-method配置的区别联系的更多相关文章
- 启动就加载(三)initializingbean实现afterPropertiesSet方法
TransactionTemplate,就直接以TransactionTemplate为入口开始学习. TransactionTemplate的源码如下: public class Transacti ...
- 用spring的 InitializingBean 的 afterPropertiesSet 来初始化
void afterPropertiesSet() throws Exception; 这个方法将在所有的属性被初始化后调用. 但是会在init前调用. 但是主要的是如果是延迟加载的话,则马上执行. ...
- Spring的InitializingBean与DisposableBean方法
在bean初始化的时候,将所有显示提供的属性设置完毕后调用这个方法 org.springframework.beans.factory.InitializingBean#afterProperties ...
- spring中afterPropertiesSet方法与init-method配置描述
1. InitializingBean.afterPropertiesSet()Spring中InitializingBean接口类为bean提供了定义初始化方法的方式,它仅仅包含一个方法:after ...
- spring init method destroy method
在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. ...
- java代码中init method和destroy method的三种使用方式
在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. ...
- 五 Action访问方法,method配置,通配符(常用),动态
1 通过method配置(有点low) 建立前端JSP:demo4.jsp <%@ page language="java" contentType="text/h ...
- Spring afterPropertiesSet方法
1.init-method方法,初始化bean的时候执行,可以针对某个具体的bean进行配置.init-method需要在applicationContext.xml配置文档中bean的定义里头写明. ...
- 用spring的InitializingBean作初始化
org.springframework.beans.factory包下有一个接口是InitializingBean 只有一个方法: /** * Invoked by a BeanFactory af ...
随机推荐
- Asp.Net采集网页方法大全(5种)
/// <summary>方法一:比较推荐 /// 用HttpWebRequest取得网页源码 /// 对于带BOM的网页很有效,不管是什么编码都能正确识别 /// </summar ...
- 阿里druid连接池监控配置
首先在web.xml中添加如下配置: <filter> <filter-name>DruidWebStatFilter</filter-name> <filt ...
- 在Windows上弄一个redis的docker容器
[本文出自天外归云的博客园] Docker核心概念简介 镜像是一个面向docker引擎的只读模板,包含了文件系统. 镜像是创建容器的基础,容器类似于一个沙箱,用来运行和隔离应用. 容器是从镜像创建的应 ...
- poj1753(位运算压缩状态+bfs)
题意:有个4*4的棋盘,上面摆着黑棋和白旗,b代表黑棋,w代表白棋,现在有一种操作,如果你想要改变某一个棋子的颜色,那么它周围(前后左右)棋子的颜色都会被改变(白变成黑,黑变成白),问你将所有棋子变成 ...
- [转载]CMMI之功能点估算法:EI、EQ和EO
EI.EO.EQ EI是处理来自于应用程序边界外部的一组数据的输入,它的主要目的是维护一个或多个ILF,以及/或者更改系统的行为. EO是输送数据到应用程序边界外部的过程.它的主要目的是通过逻辑处理过 ...
- 消息队列RabbitMQ基础知识详解
一: 什么是MQ? MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序或者模块对模块的通信方法.MQ是消费-生产者模型的一个典型的代表,一端往消息队列中不断写入消息,而另 ...
- 用Python从零开始实现K近邻算法
KNN算法的定义: KNN通过测量不同样本的特征值之间的距离进行分类.它的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别.K通 ...
- MyEclipse10中配置开发Python所需要的PyDev 绝对靠谱 不忽悠!
在NLP(自然语言处理)这个领域中,Python具有良好的声誉,于是也想学习一下.首先第一步就是需要在计算机上配置Python环境.由于Python自带的编辑器太简单,使用起来不顺手,于是就考虑在相对 ...
- OKR
不得不佩服老外对概念的提炼能力.一套一套的. Mission Vision Strategic Objectives Key Results Tasks
- [加密]ESP32 -Secure Boot 安全方案
转自:https://blog.csdn.net/espressif/article/details/79362094 Secure Boot 功能概述 方案概述 Secure Boot 的目的是保证 ...