spring三种实例化bean的方式


===============

PersonServiceBeanFactory.java

===============

package blog.service.impl;


public class PersonServiceBeanFactory {
	public static PersonServiceBean createPersonServiceBean(){
		return new PersonServiceBean();
	}
	public PersonServiceBean createPersonServiceBean2(){
		return new PersonServiceBean();
	}
}

==============

beans.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-2.5.xsd">
           
           <!-- id属于xml所有的属性,是确定bean唯一的属性,不能包含特殊字符   建议第一个字母小写 -->
           <!-- name属性可以包含特殊字符,当不包含特殊字符时应选用id来表示bean,id可以被xml解析 -->
            
            <!-- 使用类构造器方法创建bean -->
          <bean id="personService" class="blog.service.impl.PersonServiceBean" ></bean>
           
           <!-- 使用静态工场方法创建bean -->
           <bean id="personService2" class="blog.service.impl.PersonServiceBeanFactory" 
           factory-method="createPersonServiceBean"></bean>
           
           <!-- 使用实例工场方法实例化 -->
           <bean id="PersonServiceBeanFactory" class="blog.service.impl.PersonServiceBeanFactory"></bean>
           <bean id="personService3" factory-bean="PersonServiceBeanFactory" factory-method="createPersonServiceBean2"></bean>
</beans>

=================

springtest.java

=================

package junit.test;


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

import blog.service.PersonService;
import blog.service.impl.PersonServiceBean;

public class springtest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}
	
	@Test
	public void instanceSpring(){//实例化spring容器
		//使用:在类路径寻找配置文件来实例化容器
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService = (PersonService)ctx.getBean("personService");
		personService.save();
		PersonService personService2 = (PersonService)ctx.getBean("personService2");
		personService2.save();
		PersonService personService3 = (PersonService)ctx.getBean("personService3");
		personService3.save();
	}
}



转载于:https://www.cnblogs.com/xzf007/archive/2012/07/28/2873831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值