工厂实例化Bean与生命周期

静态工厂实例化Bean:

static的特点,不需要实例化工厂,直接就通过类名可以访问方法

关键点:

通过静态工厂来对实体类进行管理

必须要有一个静态方法

public class Static_factory {
	private static Map<Integer,Kc_class> kc;
	static {
		kc=new HashMap<Integer, Kc_class>();
		kc.put(1, new Kc_class("java"));
		kc.put(2, new Kc_class("android"));
		kc.put(3, new Kc_class("毛概"));
	}
	public static Kc_class getKc_class(int id) {
		return kc.get(id);
	}
}

在spring配置文件中:

必须要配置静态方法

<bean id="kc" class="factory.Static_factory" factory-method="getKc_class">
		<constructor-arg value="1"/>
		</bean>

在测试中:

获取Bean之后,是赋值给实体类

ClassPathXmlApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
		Kc_class c=(Kc_class) appCon.getBean("kc");
		System.out.println(c.getKc());

实例(动态)工厂实例化Bean

以实例化工厂的方式管理实体类

public class Dynamic_factory {
	private Map<Integer,Kc_class> kc;
	public Dynamic_factory(){
		kc=new HashMap<Integer, Kc_class>();
		kc.put(1, new Kc_class("java"));
		kc.put(2, new Kc_class("android"));
		kc.put(3, new Kc_class("毛概"));
	}
	public Kc_class getKc_class(int id) {
		return kc.get(id);
	}
}

不能直接通过类名来访问方法,所以要创建2个Bean,对于工厂本身要实例化

<bean id="df" class="factory.Dynamic_factory"></bean>
		<bean id="kc" factory-bean="df" factory-method="getKc_class">
		<constructor-arg value="1"/>
</bean> 
ClassPathXmlApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
		Kc_class c=(Kc_class) appCon.getBean("kc");
		System.out.println(c.getKc());

生命周期

public class BeanLife {
	public void init() {
		System.out.println("初始化方法开始......");
	}
	public void destroy() {
		System.out.println("摧毁方法开始执行......");
	}
}

如果Bean在Spring配置文件中配置了init-method属性,将自动调用其配置的初始化方法。

如果在配置文件中通过destroy-method属性指定了Bean的销毁方法,将调用其配置的销毁方法进行销毁。

<bean id="life" class="beanLife.BeanLife" 
		 init-method="init" destroy-method="destroy" ></bean>

init_method:初始化

destroy-method:摧毁

void test() {
		ClassPathXmlApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
		Kc_class c=(Kc_class) appCon.getBean("kc");
		System.out.println(c.getKc());
		appCon.close();
}

初始化appCon则运用初始化方法

appCon.close();则运用摧毁方法

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值