從Spring2.5開始,它引入了一種全新的依賴注入方式,即經過@Autowired註解。這個註解容許Spring解析並將相關bean注入到bean中。java
這個註解能夠直接使用在屬性上,再也不須要爲屬性設置getter/setter訪問器。spring
@Component("fooFormatter")
public class FooFormatter {
public String format() {
return "foo";
}
}
在下面的示例中,Spring在建立FooService時查找並注入fooFormatter函數
@Component
public class FooService {
@Autowired
private FooFormatter fooFormatter;
}
@Autowired註解可用於setter方法。在下面的示例中,當在setter方法上使用註釋時,在建立FooService時使用FooFormatter實例調用setter方法:學習
public class FooService {
private FooFormatter fooFormatter;
@Autowired
public void setFooFormatter(FooFormatter fooFormatter) {
this.fooFormatter = fooFormatter;
}
}
這個例子與上一段代碼效果是同樣的,可是須要額外寫一個訪問器。this
@Autowired註解也能夠用在構造函數上。在下面的示例中,當在構造函數上使用註釋時,在建立FooService時,會將FooFormatter的實例做爲參數注入構造函數:spa
public class FooService {
private FooFormatter fooFormatter;
@Autowired
public FooService(FooFormatter fooFormatter) {
this.fooFormatter = fooFormatter;
}
}
補充:在構造方法中使用@Autowired,咱們能夠實如今靜態方法中使用由容器管理的Bean。orm
@Component public class Boo { private static Foo foo; @Autowired private Foo foo2; public static void test() { foo.doStuff(); } }
定義Bean時,咱們能夠給Bean起個名字,以下爲barFormatterblog
@Component("barFormatter")
public class BarFormatter implements Formatter {
public String format() {
return "bar";
}
}
當咱們注入時,能夠使用@Qualifier來指定使用某個名稱的Bean,以下:get
public class FooService {
@Autowired
@Qualifier("fooFormatter")
private Formatter formatter;
}
參考連接:form