您的位置:首页 > 编程语言 > Java开发

spring学习笔记整理--03(Spring的三种实例化Bean的方式)

2011-02-06 16:06 786 查看
Spring有三种实例化Bean的方式

一.构造器注入实例化

  前面一个帖子的实现就是用构造器实现,也是最普遍用到的一种,在此不过多的描述。

  <bean id="personService" class="cn.service.impl.PersonServiceImpl"></bean>

二.使用静态工厂方法实例化


三.使用实例工厂方法实例化

PersonServiceFactory :
package cn.service.impl;

public class PersonServiceFactory {

public PersonServiceImpl createPersonServiceImpl(){
return new PersonServiceImpl();
}
}
-------------------------------------------------------------------------
<?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"> 
<bean id="personServiceFactory" class="cn.service.impl.PersonServiceFactory"></bean>
<bean id="personService" factory-bean="personServiceFactory" factory-method="createPersonServiceImpl"></bean>

</beans>
-------------------------------------------------------------------------
package junit.test;

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

import commons.tz.TzClassPathXmlApplicationContext;

import cn.service.PersonService;

public class Spring02Test {

@Test
public void instanceSping() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService) ctx.getBean("personService");
personService.save();
}
}


今天学的不多,偷个懒!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: