从spring容器中得到bean_使用类构造器实例化_使用静态工厂方法实例化_使用实例工厂方法实例化_例子

 

从spring容器中得到bean 使用类构造器实例化 使用静态工厂方法实例化 使用实例工厂方法实例化 例子

 

1.使用类构造器实例化

<bean id=“orderService" class="cn.itcast.OrderServiceBean"/> 

 

2.使用静态工厂方法实例化

<bean id="personService" class="cn.itcast.service.OrderFactory" factory-method="createOrder"/>

public class OrderFactory {

  public static OrderServiceBean createOrder(){

  return new OrderServiceBean();

  }

}

3.使用实例工厂方法实例化:

<bean id="personServiceFactory" class="cn.itcast.service.OrderFactory"/>

<bean id="personService" factory-bean="personServiceFactory" factory-method="createOrder"/>

public class OrderFactory {

  public OrderServiceBean createOrder(){

  return new OrderServiceBean();

  }

}

 

例子

一、PersonServiceBean.java(继承了PersonService接口,实现了接口中的save()方法)

package com.dwt1220;

public class PersonServiceBean implements PersonService {
	public void save() {
		System.out.println("这是save方法");
	}
}

 

二、PersonServiceFactory.java 工厂类

package com.dwt1220;

public class PersonServiceFactory {
	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">
	
	<!-- 使用类构造器实例化 -->
	<bean id="personService" class="com.dwt1220.PersonServiceBean" />
	
	<!-- 使用静态工厂方法实例化 -->
	<bean id="personService2" class="com.dwt1220.PersonServiceFactory" factory-method="createPersonServiceBean" />
	
	<!-- 使用实例工厂方法实例化  -->
	<bean id="personServiceFactory" class="com.dwt1220.PersonServiceFactory" />
	<bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonServiceBean2" />

</beans>



四、从spring容器中得到bean

Test.java

package com.dwt1220;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		/*******************使用类构造器实例化****************************/
		PersonService personService = (PersonService) ctx.getBean("personService");
		personService.save();
		System.out.println("使用类构造器实例化\n");
		
		/*******************使用静态工厂方法实例化****************************/
		PersonService personService2 = (PersonService) ctx.getBean("personService2");
		personService2.save();
		System.out.println("使用静态工厂方法实例化\n");

		/*******************使用实例工厂方法实例化****************************/
		PersonService personService3 = (PersonService) ctx.getBean("personService3");
		personService3.save();
		System.out.println("使用实例工厂方法实例化\n");

	}

}



 

 

你可能感兴趣的