zoukankan      html  css  js  c++  java
  • [sping]xml配置文件中factorybean与factorymethod(spring使用工厂方法注入bean)

    public class CarFactory {
       //非静态方法
       public Car createCar(){
           Car car = new Car();
           car.setBrand("BMW");
           return car;
       }
       
       //静态方法
       public static Car createStaticCar(){
           Car car = new Car();
           return car;
       }
    }

    1.对于非静态方法createCar的注入方式:

    非静态方法:必须实例化工厂类(factory-bean)后才能调用工厂方法

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
        <!-- 工厂方法-->
        <bean id="carFactory" class="com.baobaotao.ditype.CarFactory" />
        <bean id="car5" factory-bean="carFactory" factory-method="createCar">
        </bean>
    
    
    </beans>

    2.对于静态方法createStaticCar的注入方式:

    静态方法:无须创建工厂类实例的情况下就可以调用工厂类方法

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
        <bean id="car6" class="com.baobaotao.ditype.CarFactory"
            factory-method="createStaticCar"></bean>
    
    </beans>

    总结:

    factory-bean:用于实例化工厂类;

    factory-method:用于调用工厂类方法。

  • 相关阅读:
    poj 3714 Raid(平面最近点对)
    hdu 4638 Group(离线+树状数组)
    UVa 10294(polya 翻转与旋转)
    hdu 4633 Who's Aunt Zhang(polya+逆元)
    Use of Function Arctan
    codeforces 299E Cube Problem
    UVa11806 Cheerleaders(容斥原理)
    UVa11538 A Chess Queen
    UVa11401
    周报(2017.3.19-3.16)
  • 原文地址:https://www.cnblogs.com/vickylinj/p/9474597.html
Copyright © 2011-2022 走看看