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) #调用父类的方法 # ...
随机推荐
- rest_framework视图
知识预览 视图 回到顶部 视图 使用混合(mixins) 上一节的视图部分: from rest_framework.views import APIView from rest_framewor ...
- .bash_profile does not exist
localhost:test jerry$ open .bash_profile The file /Users/je/Desktop/test/.bash_profile does not exis ...
- 创建SSM项目所需
一.mybatis所需: 1.相关jar包 2.创数据库+Javabean类 3.接口+写SQL的xml映射文件 4.核心配置文件:SqlMapConfig.xml 二.springMVC所需: 1. ...
- JVM参数的配置及意义
JVM参数设置.分析 因为在工作中遇到了JVM参数的配置,不明白,网上搜索发现一篇好文,转载至:https://www.cnblogs.com/redcreen/archive/2011/05/04/ ...
- Web渗透之mssql LOG备份getshell
log备份的总结 当SQL注入是得到DB权限时候,接下来可以做的工作很多,象找管理员密码,后台管理这些都可以帮助你拿到WEBSHELL,但是这篇文章讲的是log备份,LOG备份出来的小马的体积小,而且 ...
- 实验吧之【拐弯抹角】(url伪静态)
题目地址:http://ctf5.shiyanbar.com/indirection/ 打开后给了源码 <?php // code by SEC@USTC echo '<html>& ...
- [BZOJ2392][HAOI2011]Problem c
Description 给n个人安排座位,先给每个人一个1~n的编号,设第i个人的编号为ai(不同人的编号可以相同),接着从第一个人开始,大家依次入座,第i个人来了以后尝试坐到ai,如果ai被占据了, ...
- oracle初级系列教程
https://www.cnblogs.com/linjiqin/category/349944.html
- python编程系列---白痴女朋友(我没有女朋友!)看了都能懂的TCP/IP协议介绍
前言 早期的计算机网络,都是由各厂商自己规定一套协议,IBM.Apple和Microsoft都有各自的网络协议,互不兼容:为了把全世界的所有不同类型的计算机都连接起来,就必须规定一套全球通用的协议,为 ...
- idea的各种牛逼插件
Translation : 一款免费的解决对话框的翻译插件 MyBatisCodeHelper-Pro: 功能类似mybatis plugin,我的文章有破解的教程 地址:破解