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) #调用父类的方法 # ...
随机推荐
- PCIE DMA实现
基于Spartan-6, Virtex-5/Virtex-6/Virtex-7/7 Series FPGA PCI Express Block Endpoint模块设计PCI Express Endp ...
- SQL SERVER数据库多条件查询
例如:查询挂号超500的数据select CONVERT(VARCHAR(10),DGH,23),COUNT(*) from yxhis2017..VTBMZGHMX2017 where bth=0 ...
- C# .Net Framework
.NET Framework概述 .NET Framework是由微软开发,一个致力于敏捷软件开发.快速应用开发.平台无关性和网络透明化的软件开发平台. .NET Framework组成 .NET F ...
- 关于padding被计算在width中问题——box-sizing相关
目录 盒子模型 与box-sizing有什么关系 我们为什么要开历史的"倒车" bootstrap怎么解决的 控件的box-sizing 注意甄别 前一阵子遇到一个小问题,在同样的 ...
- 利用Echarts实现全国各个省份数据占比,图形为中国地图
最近项目需求,需要一个对于全国各个省份的数据分析,图形最好是地图的样子,这样子更为直观. 最先想到的图表插件是Echarts,他的文档相对于阿里的G2,G6更加清晰一些.在Echarts 里找到的个 ...
- 实验吧之【你真的会PHP吗?】
你真的会PHP吗? 首先刚进网页就是一个have fun 看了源码没有什么提示,也没有输入框,那就打开F12看看 有提示 6c525af4059b4fe7d8c33a.txt 访问 http://c ...
- Javascript字符串常用方法详解
字符串 字符串就是一个或多个排列在一起的字符,放在单引号或双引号之中. 'abc'"abc" length属性 js里的字符串类似于数组,都是一个一个字符拼凑在一起组成的,因此可以 ...
- oracle计算两个时间的差值(XX天XX时XX分XX秒)
在工作中需要计算两个时间的差值,结束时间 - 开始时间,又不想在js里写function,也不想在java里去计算,干脆就在数据库做了一个函数来计算两个时间的差值.格式为XX天XX时XX分XX秒: 上 ...
- win7更新,360手机安装谷歌框架
这两天把11平台被卸载了,不能打竞技场了,很伤心. 成年男子,总要找点有趣的事情去做.我准备洗心革面,好好学习.(巴拉巴拉巴拉一万字.) 首先第一件事情就是重装系统,(由于买了个假显卡,win10以上 ...
- Python标准库---random模块的使用
更新时间:2019.09.12(更新目录) 目录 1. 谈谈随机数 2. random模块 2.1 random.seed() 2.2 random.random() 2.3 random ...