Spring三种实例化Bean的方式
-
最基本的:
2 简单工厂方法:
xml:
<bean id="someBean" class="some.someBeanSimpleFactory" factory-method="create"/>
java:
public class SomeBeanSimpleFactory{
public static SomeBean create(){
new SomeBean();
}
}
public static SomeBean create(){
new SomeBean();
}
}
注意static。
3 抽象工厂方法:
xml:
<bean id="someBeanFactory" class="some.someBeanFactory"/>
<bean id="someBean" factory-bean="someBeanFactory" factory-method="create"/>
<bean id="someBean" factory-bean="someBeanFactory" factory-method="create"/>
java :
public class SomeBeanFactory{
public SomeBean create(){
new SomeBean();
}
}
public SomeBean create(){
new SomeBean();
}
}
注意不是static方法。
这3种实例化Bean的方式都是
ApplicationContext context=....;
SomeBean bean=(SomeBean)context.getBean("someBean");
SomeBean bean=(SomeBean)context.getBean("someBean");