spring第四讲
一、上次學習的內容
上次的學習是第一次接觸Spring,上次我們對pom文件相關添加了依賴,主要是對采用Spring配置文件管理Bean進行了學習
二、今天要學習的內容
(1)利用組件注解符精簡Spring配置文件
(2)配置 - configuration,注解 - annotation,記住這兩個單詞
三、實現步驟
(一)運行測試一下上次的代碼是否還完整
(二)在上一次的項目基礎上我們新建一個包lesson04,在復制lesson01中的兩個包,如圖所示,在創建一個SpringConfig類
附上相關的代碼
package net.lbd.spring.lesson04;/*** 功能:殺龍任務類*/public class SlayDragonQuest {public void embark(){System.out.println("執行殺龍任務");} } package net.lbd.spring.lesson04;import net.lbd.spring.lesson01.SlayDragonQuest;public class BraveKnight {private SlayDragonQuest slayDragonQuest;public void setSlayDragonQuest(SlayDragonQuest slayDragonQuest) {this.slayDragonQuest = slayDragonQuest;}public void embarkOnQuest(){slayDragonQuest.embark();}public void setSlayDragonQuest(net.lbd.spring.lesson04.SlayDragonQuest slayDragonQuest) {} } package net.lbd.spring.lesson04;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration //標明式Spring配置類 public class SpringConfig {@Bean //創建基于SlayDragonQuest類的public SlayDragonQuest slayDragonQuest(){return new SlayDragonQuest();}@Bean("Mike") //基于BreaveKnight類創建名為Mike的Beanpublic BraveKnight braveKnight() {BraveKnight braveKnight = new BraveKnight();braveKnight.setSlayDragonQuest(slayDragonQuest());return braveKnight;}; };(三)創建測試類TestKnight
附上相關的代碼:
package net.hw.spring.lesson04;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
?* 功能:測試騎士類
?* 作者:
?* 日期:2021年
?*/
public class TestKnight {
? ? private AnnotationConfigApplicationContext context; // 基于注解配置類的應用容器
? ? @Before
? ? public void init() {
? ? ? ? // 基于注解配置類創建應用容器
? ? ? ? context = new AnnotationConfigApplicationContext(SpringConfig.class);
? ? }
? ? @Test
? ? public void testBraveKnight() {
? ? ? ? // 根據名稱從應用容器里獲取勇敢騎士對象
? ? ? ? BraveKnight knight = (BraveKnight) context.getBean("Mike");
? ? ? ? // 勇敢騎士執行任務
? ? ? ? knight.embarkOnQuest();
? ? }
? ? @After
? ? public void destroy() {
? ? ? ? // 關閉應用容器
? ? ? ? context.close();
? ? }
}
?
(四)運行測試方法,看是否能夠成功的運行
四、課堂練習?
(一)創建接口Knight、Quest
附上相關代碼:
package net.lbd.spring.lesson02;/*** 功能:騎士接口* 作者:* 日期:*/ public interface Knight {void embarkOnQuest(); } package net.lbd.spring.lesson02;/*** 功能:任務接口* 作者:* 日期:*/ public interface Quest {void embark(); }(二)、修改類
1、SlayDragonQuest
2、RescueDamselQuest
3、DamelRescuingKnight
4、BraveKnight
(三)運行查看結果
五、遇到的問題
(一)
報錯原因,在BraveKnight里面多加了兩個靜態,刪除這倆個靜態就好了
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: 笔记本按什么是u盘启动不了怎么办 笔记本
- 下一篇: spring第五讲:aop