IOC創(chuàng)建對象的方式

1、通過無參構(gòu)造方法來創(chuàng)建

  • User.java
public class User {

   private String name;

   public User() {
       System.out.println("user無參構(gòu)造方法");
  }

   public void setName(String name) {
       this.name = name;
  }

   public void show(){
       System.out.println("name="+ name );
  }

}
  • beans.xml
<?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
       http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="user" class="com.nie.pojo.User">
       <property name="name" value="niejunyu"/>
   </bean>

</beans>
  • 測試類
@Test
public void test(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //在執(zhí)行g(shù)etBean的時(shí)候, user已經(jīng)創(chuàng)建好了 , 通過無參構(gòu)造
   User user = (User) context.getBean("user");
   //調(diào)用對象的方法 .
   user.show();
}

結(jié)果可以發(fā)現(xiàn),在調(diào)用show方法之前,User對象已經(jīng)通過無參構(gòu)造初始化了!

2、通過有參構(gòu)造方法來創(chuàng)建

  • UserT . java
public class UserT {

   private String name;

   public UserT(String name) {
       this.name = name;
  }

   public void setName(String name) {
       this.name = name;
  }

   public void show(){
       System.out.println("name="+ name );
  }

}
  • beans.xml 有三種方式編寫
<!-- 第一種根據(jù)index參數(shù)下標(biāo)設(shè)置 -->
<bean id="userT" class="com.nie.pojo.UserT">
   <!-- index指構(gòu)造方法 , 下標(biāo)從0開始 -->
   <constructor-arg index="0" value="nie"/>
</bean>
<!-- 第二種根據(jù)參數(shù)名字設(shè)置 -->
<bean id="userT" class="com.nie.pojo.UserT">
   <!-- name指參數(shù)名 -->
   <constructor-arg name="name" value="nie"/>
</bean>
<!-- 第三種根據(jù)參數(shù)類型設(shè)置 -->
<bean id="userT" class="com.nie.pojo.UserT">
   <constructor-arg type="java.lang.String" value="nie"/>
</bean>
  • 測試
@Test
public void testT(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   UserT user = (UserT) context.getBean("userT");
   user.show();
}

結(jié)論:在配置文件加載的時(shí)候。其中管理的對象都已經(jīng)初始化了!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容