有三种方式:类构造器,静态工厂,实例工厂。后两种通过调用第一个实现。
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中先实例化工厂方法,再实例对象。