Spring中Bean实例化的三种方式
本文最后更新于:5 天前
Spring中Bean实例化的三种方式
1、实用类构造器实例化(常用)
1 2 3 4 5 6 7 8 9 10 11 12
| public class Person { private String name; private Integer age;
public Person() { }
public Person(String name, Integer age) { this.name = name; this.age = age; } }
|
1 2 3 4 5 6 7 8 9
|
<bean id="person1" class="Person"></bean>
<bean id="person2" class="Person"> <constructor-arg name="name" value="李华"/> <constructor-arg name="age" value="18"/> </bean>
|
2、使用静态工厂方法实例化
1 2 3 4 5
| public class PersonStaticFactory { public static Person createPerson(String name,int age){ return new Person(name, age); } }
|
1 2 3 4 5
| <bean id="person3" class="PersonStaticFactory" factory-method="createPerson"> <constructor-arg name="name" value="李雷"/> <constructor-arg name="age" value="18"/> </bean>
|
3、使用实例工厂方法实例化
1 2 3 4 5
| public class PersonFactory { public Person createPerson(String name,int age){ return new Person(name, age); } }
|
1 2 3 4 5 6 7
| <bean id="instanceFactory" class="PersonFactory"></bean>
<bean id="person4" factory-bean="instanceFactory" factory-method="createPerson"> <constructor-arg name="name" value="韩梅梅"/> <constructor-arg name="age" value="17"/> </bean>
|
静态工厂和实例工厂都是间接通过类构造器实现实例化