首页 > 其他分享 >Spring核心接口之InitializingBean

Spring核心接口之InitializingBean

时间:2023-06-08 11:33:50浏览次数:28  
标签:InitializingBean Spring init 接口 afterPropertiesSet bean method

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

 

标签:InitializingBean,Spring,init,接口,afterPropertiesSet,bean,method
From: https://www.cnblogs.com/kisshappyboy/p/17465698.html

相关文章

  • 开发密码登陆接口用postman测试报错“key is of invalid type”
    发现为go中jwt使用错误我出错的地方为//出现错误地方为tokenClaims:=jwt.NewWithClaims(jwt.SigningMethodES256,claims)returntokenClaims.SignedString(jwtSecret)我出错的点:加密方式选择了 jwt.SigningMethodES256,应该选择jwt.SigningMethodHS256,这个H是hash的意......
  • springboot 返回流式数据
    @PostMapping("/stream")publicResponseEntity<StreamingResponseBody>stream(){StreamingResponseBodystream=out->{for(inti=0;i<3;i++){try{Thread.sleep(1000);}cat......
  • SpringCache的引入
    SpringCache是Spring提供的一套的缓存解决方案,它不是具体的缓存实现,提供了一整套的配置、接口、注解等规范,用来整合当下流行的多种缓存产品。SpringCache的引入点击查看代码<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-s......
  • SpringBoot 全局异常处理
    SpringBoot全局异常处理在使用SpringBoot开发Web应用时,异常处理是必不可少的一部分。在应用中,异常可能会出现在任何地方,例如在控制器、服务层、数据访问层等等。如果不对异常进行处理,可能会导致应用崩溃或者出现未知的错误。因此,对于异常的处理是非常重要的。在SpringBoo......
  • 【SpringCloud】Ribbon
    Ribbon负载均衡原理order-service发起user-service请求,被ribbon进行拦截;ribbon会向注册中心拉取user-service相对应的服务;注册中心返回user-service服务列表;由ribbon的负载均衡机制去选择一个服务进行访问;默认采用的是轮训的机制。负载均衡流程请求示例配置......
  • 1.4OF-CONFIG南向接口协议学习
    OF-CONFIG南向接口协议学习任务目的1、了解OF-CONFIG协议的基本原理。2、掌握使用OF_CONFIG协议配置交换机的方法。任务环境设备名称软件环境(镜像)硬件环境交换机Ubuntu14.04桌面版OpenvSwitchofconfigCPU:1核内存:2G磁盘:20G注:系统默认的账户为:管理员权......
  • spring-boot-starter-validation数据校验
    依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency> beanimportboot.annotation.Status;importlombok.AllArgsConstructor;import......
  • Spring Cloud微服务
    SpringCloud微服务SpringCloud是一个用于开发分布式系统的框架,它基于SpringBoot构建。SpringCloud提供了一些工具和库,使得开发分布式系统变得更加容易。微服务架构微服务架构是一种软件架构风格,其中应用程序被拆分成小型服务,这些服务可以独立部署、扩展和维护。每个服务都是在......
  • [网络调试]在内网接口配置nat hairpin enable测试不生效问题
    用户反馈F1030在内网接口启用nathairpinenable功能后,内网PC通过公网映射地址无法访问到内部服务器。现场F1030使用Ess9308P05版本,检查映射相关配置未发现问题。沟通了解,在公网上通过公网映射地址可以正常访问服务器,内网PC通过服务器私网地址也可以正常访问服务器,初步排除服......
  • JAVA的springboot+vue企业客户信息反馈平台,附源码+数据库+文档+PPT
    1、项目介绍企业客户信息反馈平台能够通过互联网得到广泛的、全面的宣传,让尽可能多的用户了解和熟知企业客户信息反馈平台的便捷高效,不仅为客户提供了服务,而且也推广了自己,让更多的客户了解自己。对于企业客户信息反馈而言,若拥有自己的平台,通过平台得到更好的管理,同时提升了形象......