一、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. C++——decltype

    , &cj=ci; decltype(ci) x=;//x的类型是const int decltype(cj) y=x;//y的类型是const int & decltype(cj) ...

  2. python中正则匹配之re模块

    Python中正则表达式 re:re是提供正则表达式匹配操作的模块 一.什么是正则表达式 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某个模式匹配,Python 自1.5版本起 ...

  3. 结合Poi实现可读取Excel的文件选择对话框

    第一步:ApachePoi的jar包导全,不全会出现异常. 第二步:写就完事了:此例为读取特定模板的excel,仅供参考,根据实际需求改写. package 自建包; import java.awt. ...

  4. P3224 [HNOI2012]永无乡(平衡树合并)

    题目描述 永无乡包含 nn 座岛,编号从 11 到 nn ,每座岛都有自己的独一无二的重要度,按照重要度可以将这 nn 座岛排名,名次用 11 到 nn 来表示.某些岛之间由巨大的桥连接,通过桥可以从 ...

  5. 运行Storm实例

  6. robotframework+python3+selenium之下拉框的选择---第五集

    由于我没有找到option形式的,所以借鉴其他大神的博客内容,如下: 1.F12后看见下拉框的源码是<option xxx> 2.如果F12后看到的下拉源码是这样的: <div xx ...

  7. 多线程中join的解释(转)

    文章来源:https://www.zhihu.com/question/61446671 这个join可以理解为“加入”,其含义与英语里面讲“Come on,join us”中的join类似.假设线程 ...

  8. forEarch 和 for in

    forEarch 遍历数组,遍历的过程中不能被终止,必须每一个值遍历一遍后才能停下来,for  in遍历对象中的属性 代码: <!DOCTYPE html> <html lang=& ...

  9. python异常整理

    一.操作excel 时异常 1.PermissionError: [Errno 13] Permission denied (1)原因:权限错误:[Errno 13] 权限被拒绝 错误产生的原因是文件 ...

  10. js正则判断实现18位数字

    js实现18位数字 var stuCardReg = /^[0-9]{18}/; var stuCard = $('.inp).val();//获取input框中的数值 if (!stuCardReg ...