spring初始化bean时执行某些方法完成特定的初始化操作
在项目中经常会在容器启动时,完成特定的初始化操作,如资源文件的加载等。
一 实现的方式有三种:
1.使用@PostConstruct注解,该注解作用于void方法上
2.在配置文件中配置init-method方法
<bean id="student" class="com.demo.spring.entity.Student" init-method="init2">
<property name="name" value="景甜"></property>
<property name="age" value="28"></property>
<property name="school" ref="school"></property>
</bean>
3.将类实现InitializingBean接口
package com.demo.spring.entity; import javax.annotation.PostConstruct; import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component; /**
* @author chenyk
* @date 2018年5月8日
*/
@Component("student")
public class Student implements InitializingBean{
private String name;
private int age; private School school; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
} //1.使用postconstrtct注解
@PostConstruct
public void init(){
System.out.println("执行 init方法");
} //2.在xml配置文件中配置init-method方法
public void init2(){
System.out.println("执行init2方法 ");
} //3.实现InitializingBean接口
public void afterPropertiesSet() throws Exception {
System.out.println("执行init3方法");
} }
执行结果:
执行 init方法
2018-06-11 10:09:16,195 DEBUG [AbstractAutowireCapableBeanFactory.java:1671] : Invoking afterPropertiesSet() on bean with name 'student'
执行init3方法
2018-06-11 10:09:36,459 DEBUG [AbstractAutowireCapableBeanFactory.java:1731] : Invoking init method 'init2' on bean with name 'student'
执行init2 方法
二 实现原理:
由以上执行结果可知:先执行@PostConstruct注解的方法,然后是实现了InitializingBean接口的afterPropertiesSet方法,最后执行在配置文件中配置的init-method方法。至于为什么是这个顺序,可以看源码:
在 AbstractAutowireCapableBeanFactory 类中
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
} Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} try {
//调用初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
然后进入到 invokeInitMethods 方法中
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 接口中的 afterPropertiesSet 方法
((InitializingBean) bean).afterPropertiesSet();
}
} if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//进入该方法可知通过反射的方式调用init-method方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
所以,初始化方法的执行顺序 afterPropertiesSet() > init-method()
博客园的第一篇文章。感觉博客园很干净,文章排版特别是插入代码格式看起来很舒服。就不吐槽csdn了。
spring初始化bean时执行某些方法完成特定的初始化操作的更多相关文章
- ajax验证用户名 当用户名框的数据改变时 执行ajax方法
ajax验证用户名 当用户名框的数据改变时 执行ajax方法 <html xmlns="http://www.w3.org/1999/xhtml" ><head ...
- 计算属性 vs 侦听属性 当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的
https://cn.vuejs.org/v2/guide/computed.html#基础例子 计算属性 vs 侦听属性 Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属 ...
- Spring 为Bean对象执行初始化和销毁方法
1)初始化: ①可以利用<bean>元素的init-method="方法名"属性指定初始化方法. ②指定的初始化方法是在构造方法调用后自动执行.若非单例模式,则每创建一 ...
- Spring项目启动时执行初始化方法
一.applicationContext.xml配置bean <bean id="sensitiveWordInitUtil" class ="com.hx.daz ...
- spring注解之@PostConstruct在项目启动时执行指定方法
一.注解解释 Spring的@PostConstruct注解在方法上,表示此方法是在Spring实例化该Bean之后马上执行此方法,之后才会去实例化其他Bean,并且一个Bean中@PostConst ...
- 当spring 容器初始化完成后执行某个方法
在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查. 比如检查是否使用了我们组禁止使用的Mysql的group_concat函数,如果使用了项目就不能启动,并指出 ...
- 当spring 容器初始化完成后执行某个方法 防止onApplicationEvent方法被执行两次
在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查. 比如检查是否使用了我们组禁止使用的Mysql的group_concat函数,如果使用了项目就不能启动,并指出 ...
- Spring的Bean的生命周期方法执行顺序测试
通过一个简单的Maven工程来演示Spring的Bean生命周期函数的执行顺序. 下面是工程的目录结构: 直接贴代码: pom.xml文件内容: <?xml version="1.0& ...
- Spring中Bean的生命周期方法
Bean的生命周期方法 src\dayday\Car.java package dayday;import com.sun.org.apache.xpath.internal.SourceTree;i ...
随机推荐
- 待解决问题 :JDBC indexInsert.addBatch(); 为什么不生效 PSTM
JDBC indexInsert.addBatch(); 为什么不生效 PSTM
- Linux:Day8(下) RAID
RAID:Redudant Arrays of Inexpensive(Independent) Disks 廉价(独立)冗余磁盘阵列 提高IO能力:磁盘并行读写: 提高耐用性:磁盘冗余来实现: ...
- PHP 2 语句 数据类型 字符串函数 常量
在 PHP 中,有两种基本的输出方法:echo 和 print. 在本教程中,我们几乎在每个例子中都会用到 echo 和 print.因此,本节为您讲解更多关于这两条输出语句的知识. PHP echo ...
- 02 python初学 (数字运算 逻辑运算)
运算: 5/2 -> 2.5 5//2 -> 2 取整 5%2 -> 1 取余 2**10 -> 1024 指数运算 逻辑运算符: and : 条件1 and 条件2 no ...
- javascript之Map
javascript中的map,我用的不是特别多,倒是Java中的Map或HashMap,经常用. 顺便围绕几个方面介绍一下map? 1.Map对象 Map对象是一种有对应键值对的对象,JS的Obje ...
- 机器学习三剑客之Matplotlib基本操作
Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形 . 通过 Matplotlib,可以仅需要几行代码,便可以生成绘图,线型图, ...
- redis学习(三)——List数据类型
一.概述 在Redis中,List类型是按照插入顺序排序的字符串链表.和数据结构中的普通链表一样,我们可以在其头部(left)和尾部(right)添加新的元素.在插入时,如果该键并不存在,R ...
- WPF PasswordBox不支持绑定解决方法
原文:WPF PasswordBox不支持绑定解决方法 PasswordBox的Password属性因为安全原因不支持直接绑定,可以使用依赖属性实现.直接插入代码 public class Passw ...
- SpringBoot集成Shiro安全框架
跟着我的步骤:先运行起来再说 Spring集成Shiro的GitHub:https://github.com/yueshutong/shiro-imooc 一:导包 <!-- Shiro安全框架 ...
- 如果IBM再给我一次实习机会
2014年,我拿到了IBM斯图加特R&D的实习机会.在连续被索尼和博世拒掉之后,这个实习对我来说弥足珍贵.我学的是通信专业,在这之前与编程相关的活动只有一学期的安卓Lab,还是靠抱队友大腿才及 ...