2、Spring4之Bean的兩種配置方式

TZQ_DO_Dreamer發表於2014-11-09
1. Bean 屬性的配置方式

     1). setter 方法注入(最常用的方式)

          ①. 在 Bean 中為屬性提供 setter 方法:

          public void setBrand(String brand) {
               this.brand = brand;
          }

          public void setCorp(String corp) {
               this.corp = corp;
          }

          public void setPrice(float price) {
               this.price = price;
          }

          public void setMaxSpeed(int maxSpeed) {
               this.maxSpeed = maxSpeed;
          }

        ②. 在配置檔案中使用 property 注入屬性值

          <bean id="car" class="com.atguigu.spring.ioc.Car">
               <property name="brand" value="Audi"></property>
               <property name="corp" value="一汽"></property>
               <property name="maxSpeed" value="200"></property>
               <property name="price" value="200000"></property>
          </bean>

     2). 構造器注入:

          ①. bean 中提供構造器:

          public Car(String brand, String corp, int price, int maxSpeed) {
               super();
               this.brand = brand;
               this.corp = corp;
               this.price = price;
               this.maxSpeed = maxSpeed;
          }

          public Car(String brand, String corp, float price) {
               super();
               this.brand = brand;
               this.corp = corp;
               this.price = price;
          }

          public Car(String brand, String corp, int maxSpeed) {
               super();
               this.brand = brand;
               this.corp = corp;
               this.maxSpeed = maxSpeed;
          }

          ②. 配置檔案中使用 constructor-arg 節點配置使用構造器注入屬性值

          <bean id="car2" class="com.atguigu.spring.ioc.Car">
               <constructor-arg value="Ford"></constructor-arg>
               <constructor-arg value="ChangAn"></constructor-arg>
               <constructor-arg value="250000"></constructor-arg>
               <constructor-arg value="190"/>
          </bean>

          ③. 注意:對於過載的構造器可以通過引數的型別來匹配對應的構造器


          <bean id="car3" class="com.atguigu.spring.ioc.Car">
               <constructor-arg value="Buike"></constructor-arg>
               <constructor-arg value="ShanghaiTongYong"></constructor-arg>
               <constructor-arg value="180000"></constructor-arg>
          </bean>

          <!-- 
               因為有過載的構造器:
               public Car(String brand, String corp, float price)
               public Car(String brand, String corp, int maxSpeed)
        所以必須指定使用哪一個構造器來初始化屬性值. 可以使用構造器引數的型別來選擇需要的構造器!
          -->

          解決辦法
          <bean id="car4" class="com.atguigu.spring.ioc.Car">
               <constructor-arg value="Nissan"></constructor-arg>
               <constructor-arg value="Zhengzhou"></constructor-arg>
               <constructor-arg value="210" type="int"></constructor-arg>
          </bean>

相關文章