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

Spring核心接口之InitializingBean

时间:2023-06-02 17:05:43浏览次数:32  
标签: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(); 

 }



跟多技术文章

Spring核心接口之InitializingBean_配置文件

标签:InitializingBean,Spring,init,接口,afterPropertiesSet,bean,method
From: https://blog.51cto.com/u_13538361/6404135

相关文章

  • Spring核心接口之Ordered
    一、Ordered接口介绍Spring中提供了一个Ordered接口。从单词意思就知道Ordered接口的作用就是用来排序的。Spring框架是一个大量使用策略设计模式的框架,这意味着有很多相同接口的实现类,那么必定会有优先级的问题。于是Spring就提供了Ordered这个接口,来处......
  • 如何使用Spring管理Filter和Servlet
    在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象的创建。如果要在filter或者servlet中使用spring容器管理业务对象,通常需要使用WebApplicationContextUtils.getRequiredWebApplicationContext......
  • spring为什么注入接口而不是实现类?
    首先,一般使用接口是很常用并且有益的变成技术。其次,在spring中,你可以在运行过程中注入各种实现。一个很经典的情况就是在测试阶段,注入模拟的实现类。===1.网上说jdk动态代理基于实现接口。直接注入实现类会使aop失效。没有cglib可能真的就失效了。2.解耦。假如有一天实现类的名......
  • springboot项目rabbitmq消费者消费json格式的String,出现无限循环抛出No method found
    转:springboot项目rabbitmq消费者消费json格式的String,出现无限循环抛出Nomethodfoundforclass[B     ......
  • [MyBatis]DAO层只写接口,不用写实现类
    团队开发一个项目,由老大架了一个框架,遇到了DAO层不用写接口了,我也是用了2次才记住这个事的,因为自己一直都是习惯于写DAO层的实现类,所以,习惯性的还是写了个实现类。于是遇到错误了。找不到那个方法。问了团队的人才知道,方法名和Mapper中配置的id名必须一样。实现:一、配置Spring集......
  • 【电商api接口淘宝系列分享】获得商品评论+获得淘宝店铺详情演示示例
    商品评论是电商平台中一个非常重要的功能,对于商家和消费者都具有重要的意义。以下是商品评论的重要性:帮助其他消费者做出购买决策:消费者在购物前往往会查看其他消费者对商品的评价,通过评论得知商品的好、坏之处,从而做出更准确的购买决策。提供商家改进产品的意见和建议:通过......
  • 【电商api接口系列分享】按关键字搜索商品演示示例
     在电商平台中,关键词推荐是提高用户购物体验和销售业绩的一个重要手段。它的重要性体现在以下几个方面:提升购物体验:通过关键词推荐,电商平台可以根据用户的搜索意图和行为来向其推荐相关的商品。这样可以帮助用户更快地找到自己需要的商品,提高购物体验和满意度。增加销售......
  • SpringMVC大文件分片上传/多线程上传
    ​ javaweb上传文件上传文件的jsp中的部分上传文件同样可以使用form表单向后端发请求,也可以使用ajax向后端发请求    1.通过form表单向后端发送请求         <formid="postForm"action="${pageContext.request.contextPath}/UploadServlet"method="post"e......
  • linux sh脚本启动springboot
    1、restart.sh#!/bin/bashAPP_NAME=xxxxx.jar#定义JAVA程序名LOG_FILE="$APP_NAME.log"#定义日志文件名称#查询进程并终止PID=`ps-ef|grep$APP_NAME|grep-vgrep|awk'{print$2}'`kill-9$PIDecho"$APP_NAME的进程$PID已经终止"#启动jar包,指......
  • 如果还不懂如何使用 Consumer 接口,来青岛我当面给你讲!
    背景没错,我还在做XXXX项目,还在与第三方对接接口,不同的是这次是对自己业务逻辑的处理。在开发过程中我遇到这么一个问题:表结构:一张主表A,一张关联表B,表A中存储着表B记录的状态。场景:第一步创建主表数据,插入A表;第二步调用第三方接口插入B表同时更新A表的状态。此时大家应该都......