Spring IOC創(chuàng)建對象的兩種方式
IOC創(chuàng)建對象的方式
一、 使用無參構(gòu)造創(chuàng)建對象(默認(rèn)方式)創(chuàng)建實(shí)體類
注意:屬性必須要有set方法,來完成注入
public class User { private String name; public User() { System.out.println('執(zhí)行了User類的無參構(gòu)造方法~'); } public User(String name){ this.name = name; System.out.println('執(zhí)行了User類的有參構(gòu)造方法'); } //使用無參構(gòu)造方法時,必須要設(shè)置set方法,因?yàn)樽⑷霑r 需要通過set方法注入 public void setName(String name) { this.name = name; } @Override public String toString() { return 'User{' +'name=’' + name + ’’’ +’}’; }}
配置Bean
<?xml version='1.0' encoding='UTF-8'?><beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd'> <bean class='com.test.pojo.User'> <property name='name' value='gyp'/> </bean></beans>
測試類
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext('applicationContext.xml'); User user = context.getBean('user', User.class); System.out.println(user); }}
結(jié)果:

有參構(gòu)造,不需要set方法注入
通過下標(biāo)方式注入(通過index來選擇,給有參構(gòu)造的第幾個參數(shù)注入)
(1)配置Bean
<bean class='com.test.pojo.User'> <constructor-arg index='0' value='gyp'/> </bean>
(2)測試結(jié)果

通過名字注入
(1)配置Bean
<bean class='com.test.pojo.User'> <constructor-arg name='name' value='gyp'/> </bean>
(2)測試結(jié)果

通過類型注入(不建議使用!因?yàn)楫?dāng)類里面有兩個相同類型的屬性時,無法給屬性注入)
(1)配置Bean
<bean class='com.test.pojo.User'> <constructor-arg type='java.lang.String' value='gyp'/> </bean>
(2)測試結(jié)果

總結(jié):在加載配置文件的時候,IOC就已經(jīng)創(chuàng)建好了對象!
到此這篇關(guān)于Spring IOC創(chuàng)建對象的兩種方式的文章就介紹到這了,更多相關(guān)Spring IOC創(chuàng)建對象內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Android table布局開發(fā)實(shí)現(xiàn)簡單計算器2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. phpstorm恢復(fù)默認(rèn)設(shè)置的方法步驟7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫使用方法及異常處理方案9. Vuex localStorage的具體使用10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備