---
title: "Spring学习笔记（二）（转）"
author: "/ty瑞克"
date: "2010-09-24T20:02:45Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2010-09-24T20:31:09Z"
id: 770614
url: "https://crazy4j.iteye.com/blog/770614"
---

spring提供了两种IOC轻量级容器，BeanFactory和ApplicationContext，然而这两种容器有明显的区别，前者是延迟加载初始化，只有当客户端在要访问其中受管的对象的时候才去初始化。ApplicationContext是在容器启动之后全部绑定实例化对象，然而这些bean对象的实例化是容器通过Java类提供的默认构造函数来实例化，若Java类没有提供默认构造器，则会org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personservice' 异常。容器提供了三种实例化对象的方式，包括静态工厂，实例化工厂，构造函数。 静态工厂实例化：

1 定义接口 public interface PersonService{

public void save();

}

 

2 接口实现类 public class PersonServieImpl implements PersonService{ //PersonServieImpl(int x){

} @Override public void save() { System.out.println("保存方法");

}

}

 

3 工厂类 public class PersonFactory{ public staic PersonService create(){

return new PersonServieImpl();

}

}

 

4 配置文件 &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"&gt;

 

&lt;bean id="personservice" class="com.dt.study.serviceimpl.PersonServieImpl"&gt;

&lt;/bean&gt;

 

&lt;bean id="personFactory" class="com.dt.study.util.PersonFactory" factory-method="createBean"&gt;&lt;/bean&gt;

&lt;/beans&gt;

 

5 测试类 public class SpringTest {

@Test public void savetest(){

ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml");

PersonServieImpl personimpl = (PersonServieImpl)context.getBean("personFactory"); personimpl.save(); }

}