码迷,mamicode.com
首页 > 编程语言 > 详细

Spring 使用静态工厂方式实例化Bean

时间:2014-12-20 22:13:58      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:spring   静态工厂   bean   xml   

知识点介绍:
       静态工厂顾名思义,就是通过调用静态工厂的方法来获取自己需要的对象,为了让spring管理所有对象,我们不能直接通过"工程类.静态方法()"来获取对象,而是依然通过spring注入的形式获取。
【转载使用,请注明出处:http://blog.csdn.net/mahoking

操作步骤:
1、创建Speaker对象。

/**
 * 静态工厂类
 *
 */
public class Speaker {

	private String name ;
	private String topic;
	private int timeHour;
	
	private static Speaker speaker = null;
	
	private Speaker() {

		this.name = "Jacke";
		this.topic = "play football!";
		this.timeHour = 2;
				
	}
	
	/**
	 * 工厂方法
	 * @return
	 */
	public static Speaker getInstance() {

		if(null==speaker){
			speaker = new Speaker();
		}
		return speaker;
	}
	
	/**
	 * 演讲
	 */
	public void speech() {
		System.out.println(toString());
	}


	@Override
	public String toString() {
		return "Speaker [name=" + name + ", topic=" + topic + ", timeHour="
				+ timeHour + "]";
	}
}


2、创建Spring配置文件beanLearn03.xml。

<?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.xsd">

	<!-- Learn 03使用静态工厂方式实例化Bean -->
	<!--使用有参数构造参数--> 
	<bean id="speaker03" class="com.mahaochen.spring.learn03.Speaker" factory-method="getInstance">
	</bean>

</beans>

 

3、将Spring配置文件beanLearn03.xml引入到主配置文件beans.xml中。

<!-- Learn 03  使用静态工厂方式实例化Bean -->
	<import resource="com/mahaochen/spring/learn03/beanLearn03.xml"/>

 

4、编写测试类TestSpring03.java。

public class TestSpring03 {

	public static void main(String[] args) {
		BeanFactory beanFactory = new ClassPathXmlApplicationContext("beans.xml");
		//使用静态工厂方式实例化Bean
		Speaker speaker03 = beanFactory.getBean("speaker03", Speaker.class);
		speaker03.speech();
	}
}

【转载使用,请注明出处:http://blog.csdn.net/mahoking


Spring 使用静态工厂方式实例化Bean

标签:spring   静态工厂   bean   xml   

原文地址:http://blog.csdn.net/mahoking/article/details/42045855

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!