spring創(chuàng)建對象的三種方式
1.通過構(gòu)造方法創(chuàng)建
1.1無參構(gòu)造:默認情況
1.2有參構(gòu)造創(chuàng)建:需要明確配置
需要在類中提供有參構(gòu)造方法在 applicationContext.xml 中設(shè)置調(diào)用哪個構(gòu)造方法創(chuàng)建對象
如果設(shè)定的條件匹配多個構(gòu)造方法執(zhí)行最后的構(gòu)造方法
pojo類:
package com.xt.pojo;
public class People {
private String name;
private int age;
public People() {
super();
// TODO Auto-generated constructor stub
}
public People(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "People [name=" + name + ", age=" + age + "]";
}
}
<!-- 通過有參構(gòu)造1,<constructor-arg>與有參構(gòu)造函數(shù)的順序保持一致 -->
<bean id="peo" class="com.xt.pojo.People">
<constructor-arg>
<value>hanke</value>
</constructor-arg>
<constructor-arg>
<value>18</value>
</constructor-arg>
</bean>
<!-- 通過有參構(gòu)造2-->
<bean id="peo2" class="com.xt.pojo.People">
<!-- ref 引用另一個bean value 基本數(shù)據(jù)類型或String 等 -->
<constructor-arg name="name" value="張三"></constructor-arg>
<constructor-arg name="age" value="19"></constructor-arg>
</bean>
通過實例工廠
工廠設(shè)計模式:幫助創(chuàng)建類對象.一個工廠可以生產(chǎn)多個對象.
2.2 實例工廠:需要先創(chuàng)建工廠,才能生產(chǎn)對象
2.3 實現(xiàn)步驟:
2.3.1 必須要有一個實例工廠
創(chuàng)建工廠類
package com.xt.factory;
import com.xt.pojo.People;
public class PeopleFactory {
public People newInstance(){
return new People("hd",18);
}
}
在 applicationContext.xml 中配置工廠對象和需要創(chuàng)建的對象
<!-- 通過工廠模式start -->
<!-- 1.注冊工廠 -->
<bean id="peopleFactory" class="com.xt.factory.PeopleFactory"></bean>
<bean id="peoByfactory" factory-bean="peopleFactory" factory-method="newInstance"></bean>
<!-- 通過工廠模式end -->
測試
@org.junit.Test
public void peoTest3() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
People people = (People) ac.getBean("peoByfactory");
System.out.println(people);
}
/*
運行結(jié)果:
People [name=hd, age=18]
*/
通過靜態(tài)工廠
不需要創(chuàng)建工廠,快速創(chuàng)建對象.
編寫一個靜態(tài)工廠(在方法上添加static)
package com.xt.factory;
import com.xt.pojo.People;
public class StaticFactory {
public static People getPeopleByStaticFactory() {
return new People("wulala",18);
}
}
在applicationContext.xml 中創(chuàng)建對象,不需要再創(chuàng)建factory-bean
<!-- 通過靜態(tài)工廠實現(xiàn)創(chuàng)建對象start -->
<bean id="peoByStaticFactory" class="com.xt.factory.StaticFactory" factory-method="getPeopleByStaticFactory"></bean>
<!-- 通過靜態(tài)工廠實現(xiàn)創(chuàng)建對象end -->
測試
@org.junit.Test
public void peoTest() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
People people = (People) ac.getBean("peo");
System.out.println(people);
}
/*
運行結(jié)果:
People [name=wulala, age=18]
*/
注意:無論是實例工廠模式還是靜態(tài)工廠模式,都需要對factory-method屬性賦值默伍,
只是靜態(tài)工廠模式不需要事先注冊工廠類银室,生成工廠對象器罐,不需要為factory-bean屬性賦值膨俐。
靜態(tài)工廠模式只需要將class屬性賦值為靜態(tài)工廠類的全限定路徑。
即只需要為class和factory-method屬性賦值佛呻。