资讯专栏INFORMATION COLUMN

Spring核心接口之InitializingBean

zhaofeihao / 3010人阅读

摘要:一接口说明接口为提供了属性初始化后的处理方法,它只包括方法,凡是继承该接口的类,在的属性初始化后都会执行该方法。三接口应用接口在框架中本身就很多应用,这就不多说了。

一、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.
 *
 * 

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). *

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() {
                        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配置文件:

    
        
    

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();
    }



文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70836.html

相关文章

  • Spring Bean 生命周期destroy——终极信仰

    摘要:上一篇文章生命周期之我从哪里来说明了我是谁和我从哪里来的两大哲学问题,今天我们要讨论一下终极哲学我要到哪里去初始化有三种方式销毁同样有三种方式正所谓,天对地,雨对风对对对雷隐隐,雾蒙蒙山花对海树,赤日对苍穹平仄平仄平平仄,仄平仄平仄 上一篇文章 Spring Bean 生命周期之我从哪里来 说明了我是谁? 和 我从哪里来? 的两大哲学问题,今天我们要讨论一下终极哲学我要到哪里去?sho...

    JouyPub 评论0 收藏0
  • Spring详解2.理解IoC容器

    摘要:目前建议使用与。入參是当前正在处理的,是当前的配置名,返回的对象为处理后的。如果,则将放入容器的缓存池中,并返回。和这两个接口,一般称它们的实现类为后处理器。体系结构让容器拥有了发布应用上下文事件的功能,包括容器启动事件关闭事件等。 点击进入我的博客 1 如何理解IoC 1.1 依然是KFC的案例 interface Burger { int getPrice(); } in...

    Ververica 评论0 收藏0
  • SpringMVC源码分析--ViewResolver(三)

    摘要:概述本节学习下的功能,简单来说,该类的作用就是把多个视图解析器进行组装,内部使用存储配置使用的视图解析器。总结本章介绍了类,根据测试,了解到属性不影响中配置使用的视图解析器顺序。 概述 本节学习下ViewResolverComposite的功能,简单来说,该类的作用就是把多个ViewResolver视图解析器进行组装,内部使用list存储配置使用的视图解析器。 本系列文章是基于Spri...

    fox_soyoung 评论0 收藏0
  • SpringMVC源码分析--HandlerMapping(四)

    摘要:默认支持该策略。以上是对的宏观分析,下面我们进行内部细节分析。整体流程一通过实现接口,完成拦截器相关组件的初始化调用类的方法。总结本文主要分析了的初始化过程,希望对大家有帮助。随着学习的深入,后面有时间在分析下期中涉及的关键,比如等等。 概述 本节我们继续分析HandlerMapping另一个实现类ReqeustMappingHandlerMapping,该类是我们日常开发中使用最多的...

    imccl 评论0 收藏0
  • spring提供的关于bean生命周期的接口

    摘要:在中注入注入运行结果注入使用注解正如其名在构造器之后,即在销毁之前。调用的方法构造器注入属性注入顾名思义,在这个方法里面可以拿到所有装载的并在初始化之前对某些进行修改。 先看一张图:spring4.x 企业实战 showImg(https://segmentfault.com/img/bVbbO72?w=608&h=502); spring版本:4.3.171、bean自身的生命周期接...

    Cciradih 评论0 收藏0

发表评论

0条评论

zhaofeihao

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<