Spring通过工厂方法创建对象

静态工厂

工厂类

public class AppleFactory {
	public static Apple newInstance(String color) {
		return new Apple(color);
	}
}

xml

 

        
		
		        	
		
		

测试代码

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");	
Apple hongFuShi = (Apple)context.getBean("AppleFactory");
System.out.println(hongFuShi.getColor());

输出

red

动态工厂

工厂类(与静态工厂相比只是少了static)

public class DynamicAppleFactory {
	public Apple newInstance(String color) {
		return new Apple(color);
	}
}

xml

 
  
        
       
       
       		  
        
        

测试代码

ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");		
Apple hongFuShi = (Apple)context.getBean("Apple");
System.out.println(hongFuShi.getColor());

输出

red

你可能感兴趣的:(spring)