先看一个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容器自动调用方法的两种方式的更多相关文章

  1. Spring加载properties文件的两种方式

    在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取properties里面的配置,这样后期只需要改动properties文件即可, ...

  2. Spring Boot定义系统启动任务的两种方式

    Spring Boot定义系统启动任务的两种方式 概述 如果涉及到系统任务,例如在项目启动阶段要做一些数据初始化操作,这些操作有一个共同的特点,只在项目启动时进行,以后都不再执行,这里,容易想到web ...

  3. Spring Boot 中实现定时任务的两种方式

    在 Spring + SpringMVC 环境中,一般来说,要实现定时任务,我们有两中方案,一种是使用 Spring 自带的定时任务处理器 @Scheduled 注解,另一种就是使用第三方框架 Qua ...

  4. Unity调用Android的两种方式:其一、调用jar包

    unity在Android端开发的时候,免不了要调用Java:Unity可以通过两种方式来调用Android:一是调用jar.二是调用aar. 这篇文章主要讲解怎么从无到有的生成一个jar包,然后un ...

  5. 软件调用QML的两种方式

    一.两种方式 二.方式1[对窗口的控制权在QML] 三.方式2[对窗口的控制权在C++]

  6. Spring系列之AOP实现的两种方式

    AOP常用的实现方式有两种,一种是采用声明的方式来实现(基于XML),一种是采用注解的方式来实现(基于AspectJ). 首先复习下AOP中一些比较重要的概念: Joinpoint(连接点):程序执行 ...

  7. spring的面向切面实现的两种方式

    面向切面:主要应用在日志记录方面.实现业务与日志记录分离开发. spring面向切面有两种实现方式:1.注解 2.xml配置. 1.注解实现如下: (1)配置如下: <?xml version= ...

  8. 在Spring整合aspectj实现aop的两种方式

    -----------------------------基于XML配置方案目标对象接口1 public interface IUserService { public void add(); pub ...

  9. python之子类调用父类的两种方式

    第一种方式 直接在子类中调用父类名: Vehicle.__init__(self,name,speed,load,power)#调用父类的实例 Vehicle.run(self) #调用父类的方法 # ...

随机推荐

  1. 运维自动化神器ansible之user模块

    运维自动化神器ansible之user模块 一.概述   user模块 可管理远程主机上的 用户,比如创建用户.修改用户.删除用户.为用户创建密钥对等操作. 二.参数介绍   name: 用于指定操作 ...

  2. 解决Mac安装tesserocr报错问题 Failed building wheel for

    localhost:~ jerry$ Processing /var/www/git/python/tesserocr -bash: Processing: command not found loc ...

  3. Web安全之注入点构造

    在测试过程中,经常需要自己本地构造注入点来进行SQL测试,这边分享一下,不同环境下构造SQL注入的代码. PHP+MYSQL版 <?php $con = mysql_connect(" ...

  4. 什么是IDS/IPS?

    目录   摘要 0x00 基于网络的IDS和IPS0x01 设计考虑因素0X02 IDS/IPS 总结           摘要 摘要 这篇文章主要介绍的是入侵检测系统(IDS)和入侵防御系统(IPS ...

  5. Windows 批处理入门

    Windows 批处理入门   目录 本教程概述 用到的工具 标签 简介 1.命令简介 2.符号简介 3.语句结构 4.实例讲解 本教程概述 本课我们学习windows批处理 用到的工具 cmd.ex ...

  6. Python之——python-nmap的安装与常用方法说明

    一.python-nmap安装 # yum -y install nmap #安装nmap工具# 模块pip方式安装# pip install nmap# 模块源码安装# wget http://xa ...

  7. JavaScript函数总结—越努力,越幸运!

    JavaScript 函数总结 JavaScript为web的编程脚本语言. JavaScript由三部分组成:emc(语法) dom(文档对象模型) bom(浏览器对象模型). [函数的定义] 1. ...

  8. Dubbo+Zookeeper(一)Zookeeper初识

    前面花了一段时间去学习SpringCloud的相关知识,主要是理解微服务的概念并使用SpringCloud的一系列组件实现微服务落地.学习这些组件本身是简单的,跟着操作一遍基本就会了,这也得益于Spr ...

  9. Prometheus 源码解读(一)

    Prometheus 源码解读(一) Prometheus 是云原生监控领域的事实标准,越来越来的开源项目开始支持 Prometheus 监控数据格式.从本篇开始,我将和大家一起阅读分析 Promet ...

  10. springboot使用idea打jar包

    1.如果有本地jar包依赖,放到/WEB-INF/lib下,用system类型配到pom中 <dependency> <groupId>org.wechat</group ...