自動注入和@Autowire
@Autowire不屬于自動注入!
注入方式(重要)
在Spring官網上(檔案),定義了在Spring中的注入方式一共有兩種:set方法和建構式,
也就是說,你想在A類里面注入另外一個B類,無論你是通過寫 XML檔案,或者通過 @Autowried,他們最終都是通過這個A類的set方法或者建構式,將B類注入到A類中!
換句話說,你如果A類里面沒有setB(B b){…},那你就別想通過set方法把B類注入到A類中
自動注入
首先擺出一個比較顛覆的觀點:@Autowire不屬于自動注入!
如果要討論自動注入,我們先要了解什么是自動注入,什么是手動注入,
- 手動注入:在Spring 1.x的時候,我們想要在A類中注入B類,我們只能通過在xml組態檔中,加上< property >標簽,也就是說,如果我們想在A類中注入100個類,我們就要重復著寫100個< property > ,而Spring為了我們能少碼點字,就提供了 @Autowired 注解,通過這個注解,我們就可以更加輕松的手動注入需要的類
- 自動注入:如果在A類里面,需要用到B類,C類等等…我不需要重復著寫100個< property >或者100個@Autowired,而是只需要注明需要哪些類即可
既然是自動,那就代表我啥都不用做,就連一個 @Autowire 我都不加的情況下我讓B類注入進A類,這才算真正的自動注入
證明:
首先,我們先看看最原始的,通過xml的注入類:
<bean id="exampleBean" class="examples.ExampleBean">
<!-- setter injection using the nested ref element -->
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
對應的類:
public class ExampleBean {
private AnotherBean beanOne;
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne;
}
}
這是Spring官網上的一個例子,在最開始,我們通過在XML中追加<property>屬性來為類加上其所需要的類,這種手動注入的方式十分的繁瑣,所以后面出現了@Autowire注解來進行注入!說白了,就是人們為了偷懶,用一個@Autowire注解代替了寫一大串的property屬性!(先這么理解,底層原始碼肯定不是這么做的!)這樣的話,還能說 @Autowire 是自動注入了嗎?
對于自動注入,在Spring中提供了下面4種方式(甚至我可以更加負責任的告訴你們,在Spring原始碼中有5種)

先根據官方檔案提供的4種方法進行解釋:
- no:就是不要自動裝配
- byName:通過名字進行自動裝配
- byType:通過型別進行自動裝配
- constructor:通過建構式進行自動裝配
最開始我有寫到,在Spring中,自動注入的方式就只有兩種,通過set()方法和建構式,所以 byName和 byType 都是通過 set()進行裝配的,
代碼演示:通過byType方式進行自動注入
通過在<beans>標簽的末尾加上 default-autowire="byType"來實作Spring的自動注入
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"
default-autowire="byType">
<bean id="defaultAutowireService" class="com.spring.autowiringModes.DefaultAutowireService">
</bean>
<bean id="byTypeDemo" class="com.spring.autowiringModes.ByTypeDemo"/>
</beans>
Java類:
public class DefaultAutowireService {
ByTypeDemo byTypeDemo;
public ByTypeDemo getByTypeDemo() {
return byTypeDemo;
}
public void setByTypeDemo(ByTypeDemo byTypeDemo) {
this.byTypeDemo = byTypeDemo;
}
}
啟動類:
public class XmlTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
DefaultAutowireService bean =
context.getBean("defaultAutowireService", DefaultAutowireService.class);
System.out.println(bean.getByTypeDemo());
}
}
控制臺:

如果這時我們把xml檔案中的default-autowire去掉,重新啟動程式并查看控制臺:

紙上得來終覺淺,絕知此事要躬行!希望大家也可以自己寫寫代碼再驗證一下!如果有任何問題,或者我有那些地方有錯誤希望都大家可以私信我!
感謝閱讀!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/179429.html
標籤:其他
