在项目中经常会在容器启动时,完成特定的初始化操作,如资源文件的加载等。

一 实现的方式有三种:

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时执行某些方法完成特定的初始化操作的更多相关文章

  1. ajax验证用户名 当用户名框的数据改变时 执行ajax方法

    ajax验证用户名 当用户名框的数据改变时 执行ajax方法 <html xmlns="http://www.w3.org/1999/xhtml" ><head ...

  2. 计算属性 vs 侦听属性 当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的

    https://cn.vuejs.org/v2/guide/computed.html#基础例子 计算属性 vs 侦听属性 Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属 ...

  3. Spring 为Bean对象执行初始化和销毁方法

    1)初始化: ①可以利用<bean>元素的init-method="方法名"属性指定初始化方法. ②指定的初始化方法是在构造方法调用后自动执行.若非单例模式,则每创建一 ...

  4. Spring项目启动时执行初始化方法

    一.applicationContext.xml配置bean <bean id="sensitiveWordInitUtil" class ="com.hx.daz ...

  5. spring注解之@PostConstruct在项目启动时执行指定方法

    一.注解解释 Spring的@PostConstruct注解在方法上,表示此方法是在Spring实例化该Bean之后马上执行此方法,之后才会去实例化其他Bean,并且一个Bean中@PostConst ...

  6. 当spring 容器初始化完成后执行某个方法

    在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查. 比如检查是否使用了我们组禁止使用的Mysql的group_concat函数,如果使用了项目就不能启动,并指出 ...

  7. 当spring 容器初始化完成后执行某个方法 防止onApplicationEvent方法被执行两次

    在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查. 比如检查是否使用了我们组禁止使用的Mysql的group_concat函数,如果使用了项目就不能启动,并指出 ...

  8. Spring的Bean的生命周期方法执行顺序测试

    通过一个简单的Maven工程来演示Spring的Bean生命周期函数的执行顺序. 下面是工程的目录结构: 直接贴代码: pom.xml文件内容: <?xml version="1.0& ...

  9. Spring中Bean的生命周期方法

    Bean的生命周期方法 src\dayday\Car.java package dayday;import com.sun.org.apache.xpath.internal.SourceTree;i ...

随机推荐

  1. vue项目,ie11 浏览器报 Promise 未定义的错误

    报错:  {description: "“Promise”未定义", message: "“Promise”未定义", name: "Referenc ...

  2. Mac OS 安装Wget

    没有Wget的日子是非常难过的,强大的Mac OS 下安装Wget非常简单 下载一个Wget的源码包,http://www.gnu.org/software/wget/ 安装与配置 1. 首先下载一个 ...

  3. nginx指定配置文件启动

    /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

  4. echart自定义浮窗 增加点击事件

    一:情景 做一个柱状图,需要在柱状图显示lable,并且浮窗上每个条目可以被点击或者跳转. 我使用的做图插件是echarts,但是echart的浮窗是图片,而且不可以被点击,不能识别html,而且这个 ...

  5. WPF---Binding学习(一)

    转自:http://blog.csdn.net/lisenyang/article/details/18312199 1,Data Binding在WPF中的地位 程序的本质是数据+算法.数据会在存储 ...

  6. object detection[YOLO]

    这部分,我们来聊聊YOLO. YOLO:You Only Look Once,顾名思义,就是希望网络在训练过程中,一张图片只要看一次就行,不需要去多次观察,比如滑框啥的,从而从底层原理上就减少了很多的 ...

  7. Docker存储卷(V18.X)

    简介 介绍 Docker的存储卷称之为volume,本质上容器上的一个或者多个目录,而这些目录绕过了联合文件系统,与宿主机中的目录或者其他容器目录进行了绑定关系,这种绑定关系可以看作Linux的mou ...

  8. java eclipse jdk 关系

    java 经常用到多个jdk版本 1.7   1.8.... 兼容时几个位置 处理 eclipse.ini (A处) #-vm#C:\Program Files\Java\jdk1.7.0_79\bi ...

  9. Maven学习第3期---m2eclipse使用

    一.m2eclipse简介 和Nexus一样,m2eclipse也是Sonatype出品的一款开源工具,它基于Eclipse Public License-v.10开源许可证发布,用户可以免费下载并使 ...

  10. Sequelize 连接微软云数据库 SQL Azure

    function getConnection(){ var sequelize=new Sequelize("DBName","sa","000000 ...