首页 > 代码库 > Spring基础(3) : 静态工厂和实例工厂创建bean

Spring基础(3) : 静态工厂和实例工厂创建bean

public class Factory {
    public static Person staticCreate(){
        Person p = new Person();
        p.name="staticCreate";
        return p;
    }

    public Person instanceCreate(){
        Person p = new Person();
        p.name="instanceCreate";
        return p;
    }
}

  public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("a.xml");
        Person p1 = context.getBean("p1",Person.class);
        Person p2 =context.getBean("p2",Person.class);
        System.out.println(p1.getName()+" "+p2.getName());
    }

配置:
<bean id="p1" class="com.Factory" factory-method="staticCreate"/> <bean id="fac" class="com.Factory"/> <bean id="p2" factory-bean="fac" factory-method="instanceCreate"/>

通过工厂创建bean。

 

运行打印:

staticCreate instanceCreate

Spring基础(3) : 静态工厂和实例工厂创建bean