Spring依賴注入
阿新 • • 發佈:2018-12-11
內容主要來自《Spring實戰》第二章,區別在於自己寫了一個測試類,對於初學者更容易理解依賴注入。
先定義兩個介面:
1. CompactDisc.java
package soundsystem;
public interface CompactDisc {
void play();
}
2. MP.java //書上用的是MediaPlayer介面
package soundsystem;
public interface MP {
public void play();
}
再分別定義兩個類來實現上面的介面:
3. SgtPeppers.java
package soundsystem; import org.springframework.stereotype.Component; @Component public class SgtPeppers implements CompactDisc{ private String title = "Sgt.Pepper's Lonely Hearts Club Bands"; private String artist = "The Beatles"; public void play() { System.out.println("Playing "+title+" by "+artist); } }
4. CDPlayer.java
package soundsystem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CDPlayer implements MP { private CompactDisc cd; @Autowired public CDPlayer(CompactDisc cd) { this.cd = cd; } public void play() { cd.play(); } }
定義一個配置類:
5. CDPlayerConfig.java
package soundsystem;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class CDPlayerConfig {
}
最後定義一個測試類用來測試Bean是否被成功建立且自動裝配:
6. Test.java
package soundsystem; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Test { public static void main(String[] args) { // 通過Java配置來例項化Spring容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CDPlayerConfig.class); // 在Spring容器中獲取Bean物件 CDPlayer myPlayer = context.getBean(CDPlayer.class); // 呼叫物件中的方法 myPlayer.play(); // 銷燬該容器 context.destroy(); } }
build 並執行Test,如果看到資訊:“Playing Sgt.Pepper's Lonely Hearts Club Bands by The Beatles”,則說明組建掃描和自動裝配成功完成。