一、使用idea創建一個spring-boot項目,選擇groovy語言
二、編寫相應代碼
1、創建實例類
package com.zhi.example class Man { Long id String name String phone Man(Long id, String name, String phone) { this.id = id this.name = name this.phone = phone } }
2、創建service
package com.zhi.example import org.springframework.stereotype.Service @Service("manService") class ManService { Man getInfoByName(String name) { return new Man(100,name,"10000") } }
3、創建controller
package com.zhi.example import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class ManController { @Autowired private ManService manService; @GetMapping("/ok") String home() { Man man = manService.getInfoByName("tom") return "<h1>hello " + man.name + "</h1>" } }
4、運行ExampleApplication.groovy
package com.zhi.example import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class ExampleApplication { static void main(String[] args) { SpringApplication.run(ExampleApplication, args) } }
打開瀏覽器,訪問:http://localhost:8080/ok
三、代碼結構圖
四、過程中遇到的問題
1、啟動ExampleApplication.groovy報錯,“找不到或無法加載主類 com.zhi.example.ExampleApplication"
原因:這種方式是按照Java+SpringBoot啟動方式,java環境下運行一個.java文件,其實運行的是對應編譯后的.class字節碼文件,IDEA可以默認將.java編譯成.class。編譯后的.class文件在當前目錄的target文件夾下。
Groovy是用於Java虛擬機的一種敏捷的動態語言,它最終也是編譯成.class字節碼文件運行的,但IDEA默認是不會將.groovy文件進行編譯。所以我們第一次啟動會出現。找不到或無法加載到主類的異常。Source roots (or source folders) 指定一個文件夾,手動告訴
IDEA,這個文件夾及其子文件夾中包含的源代碼,可以編譯為構建過程的一部分。然后可以到target文件夾下check是否有對應的.class文件。之后就可以成功啟動SpringBoot+groovy。