SpringMVC:學習筆記(11)——依賴注入與@Autowired


SpringMVC:學習筆記(11)——依賴注入與@Autowired 

使用@Autowired

  從Spring2.5開始,它引入了一種全新的依賴注入方式,即通過@Autowired注解。這個注解允許Spring解析並將相關bean注入到bean中。

使用@Autowired在屬性上

  這個注解可以直接使用在屬性上,不再需要為屬性設置getter/setter訪問器。

@Component("fooFormatter")
public class FooFormatter {
 
    public String format() {
        return "foo";
    }
}

  在下面的示例中,Spring在創建FooService時查找並注入fooFormatter

@Component
public class FooService {
     
    @Autowired
    private FooFormatter fooFormatter;
 
}

使用@Autowired在Setters上

  @Autowired注解可用於setter方法。在下面的示例中,當在setter方法上使用注釋時,在創建FooService時使用FooFormatter實例調用setter方法:

public class FooService {
 
    private FooFormatter fooFormatter;
 
    @Autowired
    public void setFooFormatter(FooFormatter fooFormatter) {
            this.fooFormatter = fooFormatter;
    }
}

  這個例子與上一段代碼效果是一樣的,但是需要額外寫一個訪問器。

使用@Autowired 在構造方法上

  @Autowired注解也可以用在構造函數上。在下面的示例中,當在構造函數上使用注釋時,在創建FooService時,會將FooFormatter的實例作為參數注入構造函數:

public class FooService {
 
    private FooFormatter fooFormatter;
 
    @Autowired
    public FooService(FooFormatter fooFormatter) {
        this.fooFormatter = fooFormatter;
    }
}  

補充:在構造方法中使用@Autowired,我們可以實現在靜態方法中使用由容器管理的Bean

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    private Foo foo2;

    public static void test() {
        foo.doStuff();
    }
}

使用@Qualifier取消歧義

  定義Bean時,我們可以給Bean起個名字,如下為barFormatter

@Component("barFormatter")
public class BarFormatter implements Formatter {
 
    public String format() {
        return "bar";
    }
}

  當我們注入時,可以使用@Qualifier來指定使用某個名稱的Bean,如下:

public class FooService {
     
    @Autowired
    @Qualifier("fooFormatter")
    private Formatter formatter;
 
}

參考鏈接:


免責聲明!

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



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