一、InitializingBean接口说明

InitializingBean接口为bean提供了属性初始化后的处理方法,它只包括afterPropertiesSet方法,凡是继承该接口的类,在bean的属性初始化后都会执行该方法。

package org.springframework.beans.factory;

/**

* Interface to be implemented by beans that need to react once all their

* properties have been set by a BeanFactory: for example, to perform custom

* initialization, or merely to check that all mandatory properties have been set.

*

* <p>An alternative to implementing InitializingBean is specifying a custom

* init-method, for example in an XML bean definition.

* For a list of all bean lifecycle methods, see the BeanFactory javadocs.

*

* @author Rod Johnson

* @see BeanNameAware

* @see BeanFactoryAware

* @see BeanFactory

* @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName

* @see org.springframework.context.ApplicationContextAware

*/

public interface InitializingBean {

/**

* Invoked by a BeanFactory after it has set all bean properties supplied

* (and satisfied BeanFactoryAware and ApplicationContextAware).

* <p>This method allows the bean instance to perform initialization only

* possible when all bean properties have been set and to throw an

* exception in the event of misconfiguration.

* @throws Exception in the event of misconfiguration (such

* as failure to set an essential property) or if initialization fails.

*/

void afterPropertiesSet() throws Exception;

}

从方法名afterPropertiesSet也可以清楚的理解该方法是在属性设置后才调用的。

二、源码分析接口应用

通过查看spring的加载bean的源码类(AbstractAutowireCapableBeanFactory)可以看到

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)

throws Throwable {

//判断该bean是否实现了实现了InitializingBean接口,如果实现了InitializingBean接口,则调用bean的afterPropertiesSet方法

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>() {

public Object run() throws Exception {

//调用afterPropertiesSet

((InitializingBean) bean).afterPropertiesSet();

return null;

}

}, getAccessControlContext());

}

catch (PrivilegedActionException pae) {

throw pae.getException();

}

}

else {

//调用afterPropertiesSet

((InitializingBean) bean).afterPropertiesSet();

}

}

if (mbd != null) { //判断是否指定了init-method方法,如果指定了init-method方法,则再调用制定的init-method

String initMethodName = mbd.getInitMethodName();

if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&

!mbd.isExternallyManagedInitMethod(initMethodName)) {

//反射调用init-method方法

invokeCustomInitMethod(beanName, bean, mbd);

}

}

}

分析代码可以了解:

1:spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过init-method指定,两种方式可以同时使用

2:实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖

3:如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。

三、接口应用

InitializingBean接口在spring框架中本身就很多应用,这就不多说了。我们在实际应用中如何使用该接口呢?

1、使用InitializingBean接口处理一个配置文件:

import java.io.File;

import java.io.FileInputStream;

import java.util.Properties;

import org.springframework.beans.factory.InitializingBean;

public class ConfigBean implements InitializingBean{

//微信公众号配置文件

private String configFile;

private String appid;

private String appsecret;

public String getConfigFile() {

return configFile;

}

public void setConfigFile(String configFile) {

this.configFile = configFile;

}

public void afterPropertiesSet() throws Exception {

if(configFile!=null){

File cf = new File(configFile);

if(cf.exists()){

Properties pro = new Properties();

pro.load(new FileInputStream(cf));

appid = pro.getProperty("wechat.appid");

appsecret = pro.getProperty("wechat.appsecret");

}

}

System.out.println(appid);

System.out.println(appsecret);

}

}

2、配置

spring配置文件:

<bean id="configBean" class="com.ConfigBean">

<property name="configFile" value="d:/wechat.properties"></property>

</bean>

wechat.properties配置文件

wechat.appid=wxappid

wechat.appsecret=wxappsecret

3、测试

public static void main(String[] args) throws Exception {

String config = Test.class.getPackage().getName().replace('.', '/') + "/bean.xml";

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);

context.start();

}

喜欢就关注我

Spring核心接口之InitializingBean的更多相关文章

  1. spring 核心接口之 Ordered

    Spring中提供了一个Ordered接口.从单词意思就知道Ordered接口的作用就是用来排序的.Spring框架是一个大量使用策略设计模式的框架,这意味着有很多相同接口的实现类,那么必定会有优先级 ...

  2. 一文带你了解Spring核心接口Ordered的实现及应用

    前言 最近在看框架的时候,发现了这个接口,在此进行总结,希望能够给大家帮助,同时提升自己. order接口的大体介绍 Spring框架中有这个一个接口,名字叫Ordered,联想我们在数据库中应用的O ...

  3. spring中基础核心接口总结

    spring中基础核心接口总结理解这几个接口,及其实现类就可以快速了解spring,具体的用法参考其他spring资料 1.BeanFactory最基础最核心的接口重要的实现类有:XmlBeanFac ...

  4. Spring Boot REST(一)核心接口

    Spring Boot REST(一)核心接口 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) SpringBoot RE ...

  5. spring常用接口 InitializingBean的作用

    工作中遇到spring接口中的InitializingBean接口.浅浅的解说一下. --------------------------------------------------------- ...

  6. spring 的核心接口

    spring有两个核心接口,BeanFactory 和ApplicationContext  ,其中ApplicationContext 是BeanFactory的子接口.他们代表了Spring容器. ...

  7. 【Spring】Spring的事务管理 - 1、Spring事务管理概述(数据库事务、Spring事务管理的核心接口)

    Spring事务管理概述 文章目录 Spring事务管理概述 数据库事务 什么是Spring的事务管理? Spring对事务管理的支持 Spring事务管理的核心接口 Platform Transac ...

  8. Spring核心——Bean的定义与控制

    在Sring核心与设计模式的文章中,分别介绍了Ioc容器和Bean的依赖关系.如果阅读过前2文就会知道,Spring的整个运转机制就是围绕着IoC容器以及Bean展开的.IoC就是一个篮子,所有的Be ...

  9. 初识Spring——Spring核心容器

    一. IOC和DI基础 IOC-Inversion of Control,译为控制反转,是一种遵循依赖倒置原则的代码设计思想. 所谓依赖倒置,就是把原本的高层建筑依赖底层建筑“倒置”过来,变成底层建筑 ...

随机推荐

  1. arttemplate 后台返回的数据格式问题

    1. 2.JSON.parse() 方法用于将一个 JSON 字符串转换为对象. $("body").on("click","#analyze&quo ...

  2. PAT_A1048#Find Coins

    Source: PAT A1048 Find Coins (25 分) Description: Eva loves to collect coins from all over the univer ...

  3. Eureka备忘

    一. 二. 2.2. eureka集群同步集群相关重要的类com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl: 为了保证集群里所有Eur ...

  4. android是32-bit系统还是64-bit系统

    转自:http://www.cnblogs.com/pengwang/archive/2013/03/11/2954496.html 电脑CPU分32位和64位,这个我们都知道.用了这么长时间的and ...

  5. Mysql流程解析

    Mysql流程解析 流程图 流程图解析 客户端发送一条sql语句. 1.此时,mysql会检查sql语句,查看是否命中缓存,如果命中缓存,直接返回结果,不继续执行.没有命中则进入解析器. 2.解析器会 ...

  6. Linux系统的buff/cache缓存清理脚本

    cacheClean.sh #!/bin/bash # 日期: # 作者: 黄慧丰/何鹏举 # 说明: fastdfs所在的linux系统的buffer cache过大, 且并没有有效的自动回收, 因 ...

  7. 1.MySQL基础架构

    好久没发博客了,终于又学完了一点知识并且进行了整理.就从这个MySQL系列开始继续坚持每个月产出几篇. 声明一下,这次的MySQL系列是针对已有一定基础的小伙伴的,关于SQL的使用,一些概念的介绍就不 ...

  8. leetcode-159周赛-5231-删除子文件夹

    题目描述: 自己的提交: class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: d = {} r ...

  9. [JZOJ6359] 【NOIP2019模拟2019.9.15】小ω的树

    题目 题目大意 给你一棵树,带点权和边权. 要你选择一个联通子图,使得点权和乘最小边权最大. 支持修改点权操作. 思考历程 显然,最先想到的当然是重构树了-- 重构树就是在做最大生成树的时候,当两个联 ...

  10. 在myeclipse安装beyond插件

    目录 文章背景 目录 环境介绍 安装步骤 说明 参考文章 版本记录 文章背景 myeclipse自带的比较工具感觉是有一些看不清晰,也不是太方便处理,然后就找了个比较插件了. 目录 环境介绍 myec ...