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) #调用父类的方法 # ...
随机推荐
- classpath:类路径
classpath:可以用于web.xml中获取spring springmvc配置文件的位置 用于sprnig配置文件中获取mapper的位置 classpath:可以获取到java目录下的,res ...
- day 21
目录 组合 封装 访问机制 property 多态 抽象类的目的 鸭子类型 组合 组合是指的是一个对象中的属性,时另一个对象. 组合的目的和继承一样,为了减少代码冗余 封装 封装指的是把一堆属性(特征 ...
- Window下的VScode快捷键
转载自4ark 全局 Ctrl + Shift + P, F1 显示命令面板 Ctrl + P 快速打开Ctrl + Shift + N 打开新窗口Ctrl + Shift + W 关闭窗口 基本 C ...
- 02-12 Logistic(逻辑)回归
目录 逻辑回归 一.逻辑回归学习目标 二.逻辑回归引入 三.逻辑回归详解 3.1 线性回归与逻辑回归 3.2 二元逻辑回归的假设函数 3.2.1 让步比 3.2.2 Sigmoid函数图像 3.3 二 ...
- github仓库添加MIT许可
俩种方法 1.新建仓库 直接在选择添加即可如下图: 2.为已创建仓库后添加MIT协议 直接在给工程根目录添加LICENSE文件提交即可,内容是 MIT License Copyright (c) 年份 ...
- python编程基础之二十三
集合:和数学里面完全一样的,不允许有重复元素,如果添加重复元素,就会被过滤,可以进行交并差的运算 集合是可变对象 本质:无需且无重复的数据结构 创建集合 s1 = set() 括号里面可以放可迭代 ...
- 《java编程思想》P22-P37(第二章一切都是对象)
1.JAVA操纵的标识符实际上是对象的一个"引用";如String s;里的s是String类的引用并非对象. 2.程序运行时,有五个不同的地区可以存储数据. (1)寄存器:最快的 ...
- Flask-wtforms类似django中的form组件
一.安装 pip3 install wtforms 二.简单使用 1.创建flask对象 from flask import Flask, render_template, request, redi ...
- Python_函数传参
关于函数中传递参数的相关知识 其中 万能参数 第一次听说 但感觉用处不大 后面用到再详细整理
- 二、docker 镜像容器常用操作(让我们用docker 溜得飞起)
前言 上篇讲了我们如何安装docker,现在该我们一展拳脚的时候了.接下来让我们一起学习一下docker常见的操作,让我们能够会使用 docker. 基本概念 在讲使用之前,还是先将一下docker ...