现在的位置: 首页 > 综合 > 正文

spring2.5系列之———三种实例化Bean的方法

2018年02月13日 ⁄ 综合 ⁄ 共 1328字 ⁄ 字号 评论关闭

@Test
	public void test()
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		PeopleService peopleService = (PeopleService) ctx.getBean("peopleService");
		peopleService.save();
	}

	@Test
	public void test2()
	{
		TigerClassPathXMLApplicationContext ctx = new TigerClassPathXMLApplicationContext("applicationContext.xml");
		PeopleService peopleService = ((PeopleServiceBeanFactory) ctx.getBean("peopleServiceBeanFactory")).createPeopleServiceBean();
		peopleService.save();
	}
	
	@Test
	public void test3()
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		PeopleService peopleService = (PeopleService) ctx.getBean("peopleServiceBeanFactory2");
		peopleService.save();
	}

<bean id="peopleService" class="com.tiger.service.imple.PeopleServiceBean"></bean>

	<bean id="peopleServiceBeanFactory" class="com.tiger.service.imple.PeopleServiceBeanFactory"></bean>
		
	<bean id="peopleServiceBeanFactory2" factory-bean="peopleServiceBeanFactory"
		factory-method="createPeopleServiceBean2"></bean>

package com.tiger.service.imple;

public class PeopleServiceBeanFactory
{
	public static PeopleServiceBean createPeopleServiceBean()
	{
		return new PeopleServiceBean();
	}
	
	public PeopleServiceBean createPeopleServiceBean2()
	{
		return new PeopleServiceBean();
	}
}

public class PeopleServiceBean implements PeopleService
{
	public void save()
	{
		System.out.println("我是save()方法");
	}
}

结果:

我是save()方法

抱歉!评论已关闭.