`
guzizai2007
  • 浏览: 355367 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Spring学习笔记(十二)

 
阅读更多

1、抽象Bean写法:

<bean id="hello" abstract="true"/>
因为程序实例化容器的时候不会初始化abstract Bean,所以加不加class属性都无关紧要。

2、什么时候会使用到Bean的继承:

1)、应用规模增加,配置文件部分组件重复量增加,即可把这部分重复的配置信息单独调出来,定义成abstract。而实际的Bean配置成它们的子类继承就可以了。
2)、写法如下:
	<bean id="chinese" class="com.sxit.service.Chinese" abstract="true"/>
	<bean id="children" parent="chinese"/>
3)、如果父类写了class属性,则子类不需要写,如果子类写了,则以子类的class类来创建Bean实例,子类的属性会覆盖父类定义的属性。

 3、容器中的工厂Bean:

1)、这里所说的工厂Bean和之前说的不一样,这里的工厂Bean是指实现了FactoryBean接口的Bean。
2)、FacroryBean接口中有三个方法:
T getObject() ;//返回该工厂Bean生产的Java实例
Class<?> getObjectType();//返回该工厂Bean生产的Java实例的实现类
boolean isSingleton();//该工厂Bean生产的Java实例是否是单例模式

 4、工厂Bean:

package com.sxit.service;

import org.springframework.beans.factory.FactoryBean;

public class PersonFactory implements FactoryBean<Person> {

	Person p = null;
	public Person getObject() throws Exception {
		if(p == null){
			p = new Chinese();
		}
		return p;
	}

	public Class<?> getObjectType() {
		return Chinese.class;
	}

	public boolean isSingleton() {
		return true;
	}


}

5、配置文件:

<?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-3.0.xsd ">

	<bean id="personFacrory" class="com.sxit.service.PersonFactory"/>
		
</beans>

 6、测试类:

package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sxit.service.Chinese;


public class Test3 {

	public static void main(String[] args) {

		ApplicationContext apc = new ClassPathXmlApplicationContext("Bean3.xml");
		Chinese chinese = apc.getBean("personFacrory",Chinese.class);
		chinese.info("中国人");
		Chinese chinese2 = apc.getBean("personFacrory",Chinese.class);
		System.out.println(chinese == chinese2);
	}
}

 7、打印信息:

我是:中国人

8、小结:

1)、当调用getBean()方法得到的不是工厂Bean本身,而是工厂Bean负责生产的Bean,也就是getObject()里面的东西。
2)、如果需要获取工厂Bean本身,getBean("&Bean Id")即可,如下:
System.out.println(apc.getBean("&personFacrory"));
com.sxit.service.PersonFactory@10f11b8

 

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics