zoukankan      html  css  js  c++  java
  • Spring 学习总结 使用静态工厂创建Bean

    创建Bean时,class属性必须指定,此时为静态工厂类。 factory-method指定静态工厂方法名。

    接口:

    public interface Being {
    	public void testBeing();
    }
    

    Dog类

    public class Dog implements Being{
    	
    	private String msg;
    
    	public void setMsg(String msg) {
    		this.msg = msg;
    	}
    
    	@Override
    	public void testBeing() {
    		System.out.println(msg + " 狗爱啃骨头");
    		
    	}
    
    }
    

    Cat类

    public class Cat implements Being{
    
    	private String msg;
    
    	public void setMsg(String msg) {
    		this.msg = msg;
    	}
    
    	@Override
    	public void testBeing() {
    		System.out.println(msg + " 猫爱吃老鼠!");
    		
    	}
    
    }
    

     

    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"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    	<bean id="dog" class="com.springtest2.factory.BeingFactory"
    		factory-method="getBeing">
    		<constructor-arg value="dog" />
    		<property name="msg" value="我是狗" />
    	</bean>
    
    	<bean id="cat" class="com.springtest2.factory.BeingFactory"
    		factory-method="getBeing">
    		<constructor-arg value="cat" />
    		<property name="msg" value="我是猫" />
    	</bean>
    
    </beans>
    

     调用测试

    	private static void testFactory(){
    		ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"beans_factory.xml"});
    		Being b1 = context.getBean("dog", Being.class);
    		b1.testBeing();
    		
    		Being b2 = context.getBean("cat", Being.class);
    		b2.testBeing();
    	}
    

    输出结果

  • 相关阅读:
    1725最少硬币问题(DP)
    3358高数Umaru系列(9)——哈士奇(DP)
    1018骨牌铺方格(分治算法)
    3664顺序表应用7:最大子段和之分治递归法(分治算法)
    1722整数因子分解问题(分治算法)
    剑指offer JZ-11
    剑指offer JZ-10
    剑指offer JZ-9
    剑指offer JZ-8
    剑指offer JZ-7
  • 原文地址:https://www.cnblogs.com/linlf03/p/5604878.html
Copyright © 2011-2022 走看看