读书人

spring学习札记(二)

发布时间: 2012-09-03 09:48:39 作者: rapoo

spring学习笔记(二)
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 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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">

<bean id="personservice" factory-method="createBean"/>
</beans>
5 测试类
public class SpringTest {
@Test
public void savetest(){
ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml");
PersonServieImpl personimpl = (PersonServieImpl)context.getBean("personFactory");
personimpl.save();
}
}

读书人网 >软件架构设计

热点推荐