依賴注入--setting注入和構造器注入


  本文介紹依賴注入的兩種方式:setting注入和構造器注入

  這里通過一個簡單的例子來講解依賴注入的兩種方式,我們先創造一個Stage類,有了Stage就需要Performer,所以我們將

Performer注入到Stage。

  構造器注入和Setting注入

  創造兩個類Stage和Performer:

public class Performer {
    public void show() {
        System.out.println("表演ing...");
    }
}



public class Stage {
    private Performer performer;

   /* public void setPerformer(Performer performer) {
      this.performer = performer;
    }*/

  public Stage(Performer performer) {
        this.performer = performer;
    }

    public void start() {
        performer.show();
    }
}

 

  編寫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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="performer" class="Performer" />  
     <bean id="stage" class="Stage" >
<!--     使用constructor-arg則為構造器注入 -->
           <constructor-arg ref="performer"></constructor-arg>
    <!--     使用property則為setting注入
<property name="performer" ref="performer"></property> -->
      </bean>
</beans>    

  調用Stage的start方法

public class MyFirstTest {
    @Test
    public void testBean() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
        Stage stage = (Stage) ac.getBean("stage",Stage.class);
        stage.start();
    }
}

  構造器注入和setting注入都能得到bean只是xml配置的方式不一樣,當然注入也可以注入普通值,方法和上述一樣。

  有的人可能不喜歡xml配置文件,spring提供了注解的方式同樣可以實現注入。

  

  注解方式注入@Autowired和@Qualifier

  在講解注解注入時,需要了解spring自動注入的四種方式(xml配置文件中bean的autowire屬性)

  • byName:把與Bean的屬性具有相同名字(或者ID)的其他Bean自動裝配到Bean的對應屬性中,如果沒有,則該屬性不進行裝配
  • byType:把與Bean的屬性具有相同類型的其他Bean自動裝配到Bean對應屬性中,如果沒有,則該屬性不進行裝配
  • constructor:把與Bean的構造器入參具有相同類型的其他Bean自動裝配到Bean構造器的對應入參中
  • autodetect:首先嘗試使用constructor進行自動裝配,如果失敗,再嘗試使用byType

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM