《Pro Spring》学习笔记之生命周期init初始化方法

SimpleBean:

 

package  ch4_Extends;

public   class  SimpleBean  {
  
private String name;
  
private String sex;
  
private String age;
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;
}

}

 applicationContext.xml

 

<? 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.initMethod.SimpleBean"  init-method ="init" >
< 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.initMethod;

import  java.io.File;

import  org.springframework.beans.factory.BeanFactory;
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
      BeanFactory factory=(BeanFactory)getBeanFactory();  //使用子beanFactory
     
     
      SimpleBean bean1
=(SimpleBean)factory.getBean("SimpleBean");
      
    
  }

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

}

可以看到,我们在applicationContext.xml中为simpleBean配置的初始化方法已经被执行了,这个init方法已经被执行了,执行的切入点是在bean的property都注入之后,因为我们打印的name已经有值了

运行结果:

this is info from constructor from SimpleBean and property is name:gaoxiang

 

init唯一的限制就是他无法接受任何参数,虽然可以使用任意类型返回值,但spring熟视无睹

如果使用static初始化方法,这种机制就会大大折扣,因为你无法访问任何bean状态以检验之。

如果为了节省内存,你的bean使用了静态变量,同时使用static初始化方法来验证这个状态,那么应当考虑把这个静态变量转换成实例变量,并使用non-static初始化方法。

如果你使用spring的singlton管理能力,最终效果是一致的,不过这样的bean更容易测试

如果你还需要使用static变量以便让bean的多个实例之间共享数据,那么可以始终使用static的初始化方法

这种方式的好处是你的程序可以合spring分离,但你必须记得给所有需要初始化的bean配置初始化方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值