基本介紹
關(guān)于各種配置,從來沒搞懂過。但是覺得框架發(fā)展這么快,而且結(jié)構(gòu)這么宏大,其實(shí)現(xiàn)微觀上來講應(yīng)該從來沒有一種標(biāo)準(zhǔn)方式、更沒有說是固定的幾種。比如Spring專有的@Component、@Autowired注解,大多數(shù)情況下都可以被javax.inject包下的@Named和@Inject代替。本博文匯總《Spring 實(shí)戰(zhàn) 第四版》2.1和2.2內(nèi)容。
自動(dòng)裝配是使用spring滿足bean依賴的一種方法,滿足以來的過程中,spring會(huì)在應(yīng)用上下文中為某個(gè)bean尋找其依賴的bean。
Spring中bean有三種裝配機(jī)制,分別是:
1. 在xml中顯示配置;
2. 在java中顯示配置;
3. 隱式的bean發(fā)現(xiàn)機(jī)制和自動(dòng)裝配。
這里我們主要講第三種:自動(dòng)化的裝配bean。
自動(dòng)化的裝配bean
Spring的自動(dòng)裝配需要從來能個(gè)角度來實(shí)現(xiàn),或者說是兩個(gè)操作:
1.組件掃描(component scanning):spring會(huì)自動(dòng)發(fā)現(xiàn)應(yīng)用上下文中所創(chuàng)建的bean;
2.自動(dòng)裝配(autowiring):spring自動(dòng)滿足bean之間的依賴,也就是我們上篇博文說的IoC/DI;
組件掃描和自動(dòng)裝配組合發(fā)揮巨大威力,使的顯示的配置降低到最少。
一.bean自動(dòng)裝配的基本方式及測試
這里以“光碟機(jī)”和“cd播放器”為例來介紹自動(dòng)裝配的基本實(shí)現(xiàn)方式。假設(shè)我們有個(gè)光碟接口CompacDisc,其具體實(shí)現(xiàn)類為各個(gè)明星的專輯,實(shí)現(xiàn)如下:
package com.example.springboot.demo.soundsystem;
import org.springframework.stereotype.Component;
@Component//表明該類會(huì)作為組件類,告知spring為這個(gè)類創(chuàng)建bean
public class SgtPeppers implements CompactDisc {
private String title="ye hui mei";
private String artist="zhou jie lun";
@Override
public void play() {
System.out.println("playing "+title+" by "+artist);
}
}- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
通過@Component告知Spring為SgtPeppers 創(chuàng)建bean是不夠的,我們還需要讓spring知道去哪里掃描可能帶有@Component的類,盲目的全局掃描是不可行的。這里我們使用在配置類中使用@Component注解啟用組件掃描,也就是@Configuration+@ComponentScan。簡單的一逼,實(shí)例如下:
package com.example.springboot.demo.soundsystem;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; 


