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
=========================================================================================================================================
注解方式:
@Configuration public class Factory { @Bean("p1") public static Person staticCreate(){ Person p = new Person(); p.name="staticCreate"; return p; } @Bean("p2") public Person instanceCreate(){ Person p = new Person(); p.name="instanceCreate"; return p; } }
public static void main(String[] args){ ApplicationContext context = new AnnotationConfigApplicationContext(Factory.class); Person p1 = context.getBean("p1",Person.class); Person p2 = context.getBean("p2",Person.class); System.out.println(p1.getName()); System.out.println(p2.getName()); }
输出:
staticCreate
instanceCreate