欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring三种实例化bean的方式

程序员文章站 2022-06-04 23:41:22
...

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