spring中的bean
实例化spring容器常用的两种方式:
方法一:
在类路径下寻找配置文件来实例化容器
ApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
方法二:
在文件系统路径下寻找配置文件来实例化容器
ApplicationContext ctx=new FileSystemXmlApplicationContext(new String[]{"d:\\beans.xml"});
Spring的配置文件可以指定多个,可以通过String数组传入。
三种实例化bean的方式
1.使用类构造器实例化
<bean id="orderservice" class="cn.itcast.OrderServicebean"/>
2.使用静态工厂方法实例化
<bean id="personService" class="cn.itcast.service.OrderFactory" factory-method="createOrder"/>
public class OrderFactory{
public static OrderServiceBean createOrder(){
return new OrderServiceBean();
}
}
3.使用实例工厂方法实例化:
<bean id="personServiceFactory" class="cn.itcast.service.OrderFactory"/>
<bean id="personService" factory-bean="personServiceFactory" factory-method="createOrder"/>
public class OrderFactory{
public OrderServiceBean createOrder(){
return new OrderServiceBean();
}
}
public class PersonServiceBeanFactory {
public static PersonServiceBean createPersonServiceBean(){
return new PersonServiceBean();
}
public PersonServiceBean createPersonServiceBean2(){
return new PersonServiceBean();
}
}
Bean的作用域
.singleton
在每个Spring IOC容器中一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化bean,但我们可以指定Bean节点的lazy-init="true"来延迟初始化bean,这时候,只有第一次获取bean会才初始化bean。如:
<bean id="xxx" class="cn.itcast.OrderServiceBean" lazy-init="true"/>
如果想对所有bean都应用延迟初始化,可以在根节点beans设置default-lazy-init="true",如下:
<beans default-lazy-init="true"...>
.prototype
每次从容器获取bean都是新的对象
.request
.session
.global session
<?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.5.xsd" default-lazy-init="false">
<!-- default-lazy-init="false"默认(建议),设为true时对全局有效 -->
<!-- 用于配置要交于spring管理的bean类 ,id是为spring取的一个名称,名称是唯一的,name用于解决id对特殊字符的限制,用法与id样-->
<!-- class为要交于spring管理的bean类 -->
<!-- 使用类构造器实例化 -->
<!-- init-method="init"指定在初始化时要执行的初始化方法init,destroy-method="destory"在 bean销毁前执行关闭资源的方法destory-->
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" init-method="init" destroy-method="destory"></bean>
<!-- 使用静态工厂方法实例化 -->
<!-- lazy-init为延迟初始化,默认为false,为true时要进行延迟,在调用getBean()时初始化-->
<bean id="personService2" class="cn.itcast.service.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBean" lazy-init="true"/>
<!-- 使用实例工厂方法实例化 -->
<bean id="personServiceFactory" class="cn.itcast.service.impl.PersonServiceBeanFactory"/>
<bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonServiceBean2" scope="prototype"/>
<!-- scope为Bean的作用域,默认为singleton,第一次获取时初始化,以后每次获取都是相同的这个bean。prototype,每次从容器获取bean都是新的对象 -->
</beans>
public class PersonDaoBean implements PersonDao {
@Override
public void add(){
System.out.println("执行PersonDaoBean中的add()");
}
}
指定Bean的初始化方法和销毁方法
<bean id="xxx" class="cn.itcast.OrderServiceBean" init-method="init" destroy-method="close"/>
public class PersonServiceBean implements PersonService {
public void init(){
System.out.println("初始化");
}
public PersonServiceBean() {
System.out.println("我被实例化了");
}
@Override
public void save(){
System.out.println("我是save()方法");
}
public void destory(){
System.out.println("关闭打开的资源");
}
}
//用于存放读取到的Bean的信息
public class BeanDefinition {
private String id;
private String className;
public BeanDefinition(String id, String className) {
this.id = id;
this.className = className;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
-------------------------------------------------------------------------------------
public class ItcastClassPathXMLApplicationContext {
private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
private Map<String, Object> sigletons = new HashMap<String, Object>();
public ItcastClassPathXMLApplicationContext(String filename){
this.readXML(filename);
this.instanceBeans();
}
/**
* 完成bean的实例化
*/
private void instanceBeans() {
for(BeanDefinition beanDefinition : beanDefines){
try {
if(beanDefinition.getClassName()!=null && !"".equals(beanDefinition.getClassName().trim()))
sigletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 读取xml配置文件
* @param filename
*/
private void readXML(String filename) {
SAXReader saxReader = new SAXReader();//创建一个读取器
Document document=null;
try{
URL xmlpath = this.getClass().getClassLoader().getResource(filename);//取得类的类装载器
document = saxReader.read(xmlpath);//读取文件的内容得到一个document
Map<String,String> nsMap = new HashMap<String,String>();
nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间
XPath xsub = document.createXPath("//ns:beans/ns:bean");//创建beans/bean查询路径
xsub.setNamespaceURIs(nsMap);//设置命名空间
List<Element> beans = xsub.selectNodes(document);//获取文档下所有bean节点
for(Element element: beans){
String id = element.attributeValue("id");//获取id属性值
String clazz = element.attributeValue("class"); //获取class属性值
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
beanDefines.add(beanDefine);
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 获取bean实例
* @param beanName
* @return
*/
public Object getBean(String beanName){
return this.sigletons.get(beanName);
}
}
---------------------------------------------------------------------------------------------------
public class SpringTest {
@Test
public void instanceSpring() {
// 通过ApplicationContext接口引用ClassPathXmlApplicationContext这个Spring实例类。
// ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");//Scope为singleton时在容器实例化时实例化bean
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
// ItcastClassPathXMLApplicationContext ctx = new
// ItcastClassPathXMLApplicationContext("beans.xml");
// 验证Spring容器是否搭建成功,如果控制台无错误信息则搭建成功
// 获取bean的名称,
// PersonService personService = (PersonService) ctx.getBean("personService3");//Scope为prototype时调用getBean()时实例化bean
// PersonService personService2 = (PersonService) ctx.getBean("personService3");
// personService.save();
// System.out.println(personService==personService2);
ctx.close();//关闭Spring容器
}
}