《Pro Spring》学习笔记之BeanNameAware和BeanFactoryAware

本文通过一个示例详细介绍了Spring框架中Bean的生命周期管理,包括Bean的初始化、销毁过程及如何利用BeanFactoryAware等接口来实现特定的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看代码实例:

SimpleBean.java

 

package ch5.BeanAware;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import ch5.destroy.ShutDownHook;

public class SimpleBean implements InitializingBean,DisposableBean,BeanNameAware,BeanFactoryAware,Runnable {
  
private ConfigurableListableBeanFactory configurableListableBeanFactory;
  
public void setBeanName(String beanName) {
        System.out.println(
"this is info from BeanNameAware and beanName is:"+beanName);
        
    }

    
public void setBeanFactory(BeanFactory factory) throws BeansException {
        
//自动注册成线程
        if(factory instanceof ConfigurableListableBeanFactory){
            System.out.println(
"this is info from BeanNameAware and beanName");
            
this.configurableListableBeanFactory=(ConfigurableListableBeanFactory)factory;
              Runtime.getRuntime().addShutdownHook(
new Thread(this));
        }

        
    }

    
public void afterPropertiesSet() throws Exception {
        System.out.println(
"this is info from afterpropertiesSet from SimpleBean");
    }

    
public void run() {
        
//线程调用destroySingletons
        configurableListableBeanFactory.destroySingletons();
        
    }

  
private String name;
  
private String sex;
  
private String age;
  
public void destroyMethod(){
      System.out.println(
"this is info from customer destroy method");
  }

  
public void destroy(){
      System.out.println(
"this is info from destroy method");
  }

public String getAge() {
    
return age;
}

public void setAge(String age) {
    
this.age = age;
}

public String getName() {
    
return name;
}

public void setName(String name) {
    
this.name = name;
}

public String getSex() {
    
return sex;
}

public void setSex(String sex) {
    
this.sex = sex;
}

}

 配置文件:

 

<?xml version="1.0" encoding="UTF-8"?>
<beans
    
xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="SimpleBean" class="ch5.destroy.SimpleBean" destroy-method="destroyMethod">
<property name="name">
    
<value>gaoxiang</value>
  
</property>
<property name="sex">
   
<value>male</value>
</property>
<property name="age">
    
<value>26</value>
  
</property>
</bean>


</beans>

 

测试代码:

 

package ch5.BeanAware;

import java.io.File;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class TestSpring{
  
public static void main(String args[])  throws Exception{
      
//获取bean factory
      ConfigurableListableBeanFactory factory=(ConfigurableListableBeanFactory)getBeanFactory();  //使用子beanFactory
     
      factory.preInstantiateSingletons();
      SimpleBean bean1
=(SimpleBean)factory.getBean("SimpleBean");
      


  }

  
public static BeanFactory getBeanFactory(){
      
//获取bean factory
      String realpath="";
   
         
//加载配置项
      realpath=System.getProperty("user.dir")+File.separator+"src"+File.separator+"ch5/destroy"+File.separator+"applicationContext.xml";
  
     
      ConfigurableListableBeanFactory  factory
=new XmlBeanFactory(new FileSystemResource(realpath));
      
      
return factory;
  }

}

 

一点说明:

实现BeanNameAware接口需要实现setBeanName()方法,这个方法只是简单的返回我们当前的beanName

实现BeanFactoryAware,我们

 public void run() {
    
//线程调用destroySingletons
    configurableListableBeanFactory.destroySingletons();
        
}

可以调用到获得Bean的工厂,需要实现setBeanFactory方法

 

看测试程序的这段代码:

 

 ConfigurableListableBeanFactory factory=(ConfigurableListableBeanFactory)getBeanFactory();    
factory.preInstantiateSingletons();
SimpleBean bean1
=(SimpleBean)factory.getBean("SimpleBean");


我们对ConfigurableListableBeanFactory .preInstantiateSingletons();进行了调用,默认情况下,只有用到singleton Bean的时候,spring才会使用懒汉式子进行初始化,这对SimpleBean可是个大麻烦,因为它需要实例化后才能注册成为shutdown hook,调用preInstantiateSingletons()可让spring立即处理其全部的bean定义并创建实例,测试代码中并没有调用destroySingleton(),因为simpleBean已经在run方法中进行调用了。如下:

 public void run() {
     //线程调用destroySingletons
  configurableListableBeanFactory.destroySingletons();
 }

运行结果:

this is info from BeanNameAware and beanName is:SimpleBean
this is info from BeanNameAware and beanName
this is info from afterpropertiesSet from SimpleBean
this is info from destroy method
this is info from customer destroy method

也可以看到,执行顺序是BeanNameAware,BeanFactoryAware,afterPropertiesSet,customer-Init,disposeable,customer-destroy


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值