Spring MVC CRUD with Example - GeeksforGeeks

SpringBoot - 單元測試工具 Mockito

The DAO Pattern in Java | Baeldung

因為跟著教學完成一個有陽春CRUD介面的應用,因此想要寫個簡單的測試來更熟悉架構。(畢竟跟著教學做的東西不是自己發想,對金魚腦本人來說很容易忘記)

結果在尋找測試教學文章時看到“DAO”,本來以為他跟我已經寫好的介面Service, 還有應用Service的類別是同樣的概念,只是類別名字不一樣,深入暸解之後發現自己大錯特錯⋯⋯

嚴格來說,從寫法上來看他們的確是同樣的原理,介面PracticeService對應到DAO,ServiceImple對應到PracDAO,都是用來跟資料庫互動的類別。但是他們的目的完全不一樣,DAO介面通常是用來定義跟資料庫的互動方式。PracticeService會介於Controller跟DAO之間,應該要定義更複雜的業務邏輯,例如把DAO拿到的資料分頁,或是先驗證拿到的資料再傳給Controller,也可以定義其他更詳細尋找資料的方式。 總之我花了蠻多時間又找教學寫了DAO,雖然我沒把他跟Controller, Service結合在一起,但過程中我反而發現自己的盲點哈哈。我一直覺得Spring架構很複雜,搞不懂dependency還有bean是什麼,趁這次機會終於比較有頭緒了!

如果從執行順序來看,應用都會有個進入點(Entry),是從@SpringBootApplication 底下的main()開始進行初始化,它會先掃過所有標記@Component的類別,並且將他們建立成Spring容器裡的Bean,也就是容器裡的物件,而這些@Component其實就包含先前提過的@Controller , @Repository , @Service 。其中我有定義一個Bean是CommandLineRunner,可以在終端機上優先運行我寫的CRUD測試。另一個小盲點是,同樣都是用Practice這個模型,但這個DAO測試的資料都沒有被寫入我使用的h2資料庫,後來發現因為我並沒有引入能夠跟h2資料庫互動的jpa,而是使用List來儲存資料後在終端上顯示,才會造成這個差異。

I built a simple application where users can interact with a database through the frontend, so I pondered further development with testing. (Because that application is constructed following a tutorial, I think I’d have a better impression and understanding after doing it the other way.)

I accidentally found out DAO is different from the interface “Service” I wrote. Actually, they have similar syntax, but the purpose of each is analogous. The DAO interface usually defines the abstraction for interaction with the database. For the service interface, it serves as a bridge between the controller and DAO, incorporating business logic such as data pagination, authentication, or unique data retrieval methods.

After going through the other DAO tutorial, it clarified the workflow of a Spring application for me. When we start a Spring Boot application, it executes the main() method from an entry point defined in the file with @SpringBootApplication. The @Component objects like @Controller, @Repository, and @Service are constructed as beans, which are the objects in the container. I defined a CommandLineRunner bean to run the test in the terminal. While building the test, I noticed that the data I updated wasn’t being written to the database. I realized this was because I was importing different resources compared to the normal execution. Instead of using the H2 database, I was using a Java List to represent the data storage.

Execute Flow of a Spring Boots Application


  1. In my example test, the main() in class SpringBootJpaH2Application() will triggered because of the@SpringBootApplication.
  2. Then it’ll scan the @Component which i define my PracApplication() , And register @Bean CommandLineRunner in Spring container.
  3. Discover @Controller, @Service, @Repository …… , construct their beans.