工厂方法注入(静态和非静态)

先看非静态的

先写一个简单工厂

Java代码   收藏代码
  1. package com.lbx.factory;  
  2.   
  3. import com.lbx.model.Car;  
  4.   
  5. /** 
  6.  * 这是非静态的工厂方法注入 
  7.  * @author Administrator 
  8.  * 
  9.  */  
  10. public class CarFactory {  
  11.   
  12.     public Car createHongQiCar(){  
  13.         Car car = new Car();  
  14.         car.setName("红旗");  
  15.         car.setSpeed("200");  
  16.         return car;  
  17.     }  
  18.       
  19. }  

 

 

对应的bean.xml文件

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3. xmlns="http://www.springframework.org/schema/beans"  
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5. xmlns:p="http://www.springframework.org/schema/p"  
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
  8.   
  9. <bean id="carFactory" class="com.lbx.factory.CarFactory"></bean>  
  10. <bean id="car" factory-bean="carFactory" factory-method="createHongQiCar"></bean>  
  11.   
  12. </beans>  

 

 

 

 

 

再看静态的(无需依赖工厂的bean)

工厂类

Java代码   收藏代码
  1. package com.lbx.factory;  
  2.   
  3. import com.lbx.model.Car;  
  4. /** 
  5.  * 这是静态的工厂方法注入 
  6.  * @author Administrator 
  7.  * 
  8.  */  
  9. public class CarFactory2 {  
  10.   
  11.     public static Car createHongQiCar(){  
  12.         Car car = new Car();  
  13.         car.setName("红旗");  
  14.         car.setSpeed("200");  
  15.         return car;  
  16.     }  
  17.       
  18. }  

 

 

对应的bean2.xml文件

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3. xmlns="http://www.springframework.org/schema/beans"  
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5. xmlns:p="http://www.springframework.org/schema/p"  
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
  8.   
  9. <bean id="car" class="com.lbx.factory.CarFactory2" factory-method="createHongQiCar"></bean>  
  10.   
  11. </beans> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值