`
coolszy
  • 浏览: 1407105 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Sping学习笔记(2)----实例化Bean的三种方式

阅读更多

Spring的实例化Bean有三种方式:

 使用类构造器直接实例化

 使用静态工厂的方法实例化

 使用实例工厂方法实例化

 

三种方式对应的配置如下

<?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:tx="http://www.springframework.org/schema/tx"
		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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
		<!-- 使用类构造器直接实例化 -->	
		<bean id="userBean1" class="com.szy.spring.implbean.UserBean" />
		<!-- 使用静态工厂的方法实例化 -->
		<bean id="userBean2" class="com.szy.spring.factory.BeanFactory" factory-method="UserBeanService" />
		<!-- 使用实例工厂方法实例化 -->
		<bean id="factory" class="com.szy.spring.factory.BeanFactory" />
		<bean id="userBean3" factory-bean="factory" factory-method="getUserBeanService" />
</beans>

 

 

其中BeanFactory类的代码如下

package com.szy.spring.factory;

import com.szy.spring.implbean.UserBean;
import com.szy.spring.interfacebean.PersonBean;

public class BeanFactory
{
	//使用静态工厂的方法实例化使用
	public static PersonBean UserBeanService()
	{
		return new UserBean();
	}
	
	public PersonBean getUserBeanService()
	{
		return new UserBean();
	}
}

 

在这三种方式中我们最常用的还是第一种。

2
0
分享到:
评论
1 楼 CoderDream 2009-11-02  
不错,昨天刚好看了“XX播客”的Spring教程,讲到了这些东西。

相关推荐

Global site tag (gtag.js) - Google Analytics