有三種方式:類構造器,靜態工廠,實例工廠。後兩種通過調用第一個實現。
1. 類構造器
Bean:
public Class Person(){
private String name;
private Integer age;
public Person(){}
public Person(String name,Integer age){
this.name = name;
this.age =age;
}
}
applicationContext.xml
//1. 無參
<bean id="person1" class="com.imooc.spring.instance.Person" />
//2. 有參
<bean id="person2" class="com.imooc.spring.instance.Person" >
<constructor-arg name="name" value="楓葉" />
<constructor-arg name="age" value=23 />
</bean>
main
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml)
2. 靜態工廠
public class PersonStaticFactory{
public static Person createPerson(String name, Integer age){
return new Person(name,age);
}
}
xml:
<bean id="person3" class="com.imooc.spring.instance.PersonStaticFactory factory-method="createPerson">
<constructor-arg name="name" value="藍天" />
<constructor-arg name="age" value=27 />
</bean>
main
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml)
3. 實例工廠
相比於靜態工廠,在工廠方法上少了static,需要在xml中先實例化工廠方法,再實例對象。