Spring容器自动调用方法的两种方式
先看一个Spring中Bean的实例化过程:

1.配置文件中指定Bean的init-method参数
<bean class="com.jts.service.UserService" init-method="init"></bean>
缺点:注解方式实例化Bean时无法使用
2.Bean实现InitializingBean接口(推荐,Spring源码和框架搭建中大量使用)
InitializingBean接口只有一个方法afterPropertiesSet,实例化Bean时会调用该方法
注意:
1.如果两种方式同时存在,会先执行afterPropertiesSet方法后执行init-method指定的方法,原因见Spring源码AbstractAutowireCapableBeanFactory类invokeInitMethods方法
2.实现接口为直接调用afterPropertiesSet方法,配置init-method为反射调用,所有实现接口效率较高
/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the merged bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
*/
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
} if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
/**
* Invoke the specified custom init method on the given bean.
* Called by invokeInitMethods.
* <p>Can be overridden in subclasses for custom resolution of init
* methods with arguments.
* @see #invokeInitMethods
*/
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {
String initMethodName = mbd.getInitMethodName();
final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
if (initMethod == null) {
if (mbd.isEnforceInitMethod()) {
throw new BeanDefinitionValidationException("Couldn't find an init method named '" +
initMethodName + "' on bean with name '" + beanName + "'");
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No default init method named '" + initMethodName +
"' found on bean with name '" + beanName + "'");
}
// Ignore non-existent default lifecycle methods.
return;
}
} if (logger.isDebugEnabled()) {
logger.debug("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'");
} if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
ReflectionUtils.makeAccessible(initMethod);
return null;
}
});
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
initMethod.invoke(bean);
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
InvocationTargetException ex = (InvocationTargetException) pae.getException();
throw ex.getTargetException();
}
}
else {
try {
ReflectionUtils.makeAccessible(initMethod);
initMethod.invoke(bean);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
Spring容器自动调用方法的两种方式的更多相关文章
- Spring加载properties文件的两种方式
在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取properties里面的配置,这样后期只需要改动properties文件即可, ...
- Spring Boot定义系统启动任务的两种方式
Spring Boot定义系统启动任务的两种方式 概述 如果涉及到系统任务,例如在项目启动阶段要做一些数据初始化操作,这些操作有一个共同的特点,只在项目启动时进行,以后都不再执行,这里,容易想到web ...
- Spring Boot 中实现定时任务的两种方式
在 Spring + SpringMVC 环境中,一般来说,要实现定时任务,我们有两中方案,一种是使用 Spring 自带的定时任务处理器 @Scheduled 注解,另一种就是使用第三方框架 Qua ...
- Unity调用Android的两种方式:其一、调用jar包
unity在Android端开发的时候,免不了要调用Java:Unity可以通过两种方式来调用Android:一是调用jar.二是调用aar. 这篇文章主要讲解怎么从无到有的生成一个jar包,然后un ...
- 软件调用QML的两种方式
一.两种方式 二.方式1[对窗口的控制权在QML] 三.方式2[对窗口的控制权在C++]
- Spring系列之AOP实现的两种方式
AOP常用的实现方式有两种,一种是采用声明的方式来实现(基于XML),一种是采用注解的方式来实现(基于AspectJ). 首先复习下AOP中一些比较重要的概念: Joinpoint(连接点):程序执行 ...
- spring的面向切面实现的两种方式
面向切面:主要应用在日志记录方面.实现业务与日志记录分离开发. spring面向切面有两种实现方式:1.注解 2.xml配置. 1.注解实现如下: (1)配置如下: <?xml version= ...
- 在Spring整合aspectj实现aop的两种方式
-----------------------------基于XML配置方案目标对象接口1 public interface IUserService { public void add(); pub ...
- python之子类调用父类的两种方式
第一种方式 直接在子类中调用父类名: Vehicle.__init__(self,name,speed,load,power)#调用父类的实例 Vehicle.run(self) #调用父类的方法 # ...
随机推荐
- HTTP/1.1与HTTP/2有什么区别?
介绍 超文本传输协议(HTTP)是一种应用协议,自1989年发明以来,它一直是事实上在万维网上进行通信的标准.从1997年发布HTTP / 1.1到最近,对它的修改很少.协议.但是在2015年,重 ...
- 02-35 scikit-learn库之支持向量机
目录 scikit-learn库之支持向量机 一.SVC 1.1 使用场景 1.2 代码 1.3 参数详解 1.4 属性 1.5 方法 二.LinearSVC 三.NuSVC 四.LinearSVR ...
- python编程基础之十五
二维列表 l1 = [[1, 2, 3], [4, 5, 6]] print(l1[0][0]) 列表负值 列表复制为两种:深复制,浅复制 浅复制:只复制容器,容器里的元素不产生副本,只是技术引用增加 ...
- 【TencentOS tiny】深度源码分析(3)——队列
队列基本概念 队列是一种常用于任务间通信的数据结构,队列可以在任务与任务间.中断和任务间传递消息,实现了任务接收来自其他任务或中断的不固定长度的消息,任务能够从队列里面读取消息,当队列中的消息是空时, ...
- Java 语言的发展史
维基百科引入 早期的Java 语言最开始只是Sun计算机(Sun MicroSystems)公司在1990年12月开始研究的一个内部项目.Sun计算机公司的一个叫做帕特里克·诺顿的工程师被公司自己开发 ...
- 直线扫描转换-DDA算法
直线扫描转换-DDA算法 直线段的扫描转换算法 已知两个点,求直线. 为了在光栅显示器上用这些离散的像素点逼近这条直线,需要知道这些像素点的x,y坐标. 求出过P0,P1的直线段方程: y=kx+b ...
- RF分层封装
1.如何管理用例? (1).在ride工具中分层管理用例(案例层.元素层.流程层),提高效率 (2).偶尔运行下,保证脚本能正常跑动 2.用例分层操作 案例层:需要加载流程层.txt资源和Seleni ...
- 介绍ArcGIS中各种数据的打开方法——tin(栅格文件)
4.加载栅格文件 栅格数据是GIS中重要的数据源之一,如卫星图像.扫描的地图.照片等. 栅格数据常见的格式有Bmp.Tiff.Jpg.Grid等. 添加栅格数据主要使用Rasterlayer 组件类, ...
- 使用CDPATH快速cd到指定路径
CDPATH是shell的一个环境变量, 默认值为空: 将你常用的目录添加到CDPATH的目录列表中, 用':'冒号分隔, 比如, 当前目录 ., home目录 ~, 根目录 /, 等等: # 注意等 ...
- 如何用js做关灯游戏
编辑器 Sublime Text 3 <!DOCTYPE html><html lang="en"><head> <meta chars ...