springboot(基礎篇):快速構建一個springboot專案
阿新 • • 發佈:2019-01-06
前言:
springboot作為springcloud的基礎,學會springboot是必不可少的技能,所以這個系列教程一是記錄自己的學習過程,二是作為一份分享教程,幫助新手入門
springboot能做什麼
- springboot 致力於簡潔,讓開發者寫更少的配置,程式能夠更快的執行和啟動
- Springboot 設計原則就是 約定優於配置。並且內嵌了Servlet容器
- springboot 採用的是Java Config的方式,對Spring進行配置,避免了XML配置以及複雜的依賴管理,使用springboot可以幫助開發者快速搭建一個Spring框架
- springboot封裝了各種元件,使用那個就引入依賴模組即可
- 優點很多就不一一列舉了,自己上手就知道了
如何使用springboot構建一個web專案
構建一個支援web模組的springboot專案需要以下幾個步驟:
1. pom.xml引入springboot的依賴支援
2. 一個程式入口類
3. 一個專案配置檔案(預設設定不用寫也可以)
先貼一下專案目錄
- src/main/java 下的程式啟動入口:Application
- src/main/resources下的配置檔案:application.properties
新建一個maven專案:
- 在pom.xml中引入springboot的依賴
<dependencies >
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId >spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- spring-boot-starter 模板:核心模組,包括自動配置支援、日誌和YAML
- spring-boot-starter-web 模組:web模組
- 新建一個專案啟動類:Application
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication 程式啟動的註解
@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
@Configuration的註解類標識這個類可以使用Spring IoC容器作為bean定義的來源, @Bean註解告訴Spring,一個帶有@Bean的註解方法將返回一個物件,該物件應該被註冊為在Spring應用程式上下文中的bean。
@EnableAutoConfiguration:能夠自動配置spring的上下文,試圖猜測和配置你想要的bean類,通常會自動根據你的類路徑和你的bean定義自動配置。
@ComponentScan:會自動掃描指定包下的全部標有@Component的類,並註冊成bean,當然包括@Component下的子註解@Service,@Repository,@Controller。
到這裡,一個簡單的springboot就建成了
執行程式入口類:Application,檢視控制檯,發現以下輸出
Tomcat started on port(s): 8080 (http),就說tomcat已經成功啟動,預設埠是8080
- 在/resources下,新建application.properties
server.port=9001 //修改啟動埠為9001
如果配置了application.properties,則走配置項,否則走自動的預設配置,就像預設的啟動埠
重新啟動專案,訪問http://localhost:9001/
顯示的是springboot預設的錯誤頁面,為甚是錯誤頁那?
產生錯誤的原因是Not Found,404,就是沒找到首頁接下來模擬一個http請求
- 新建包:/com.my.controller
- 在其下新建類:LoginController
@RestController
public class LoginController {
@GetMapping("/sayHello")
public String login(){
return "hello xiaonuo";
}
}
@RestController註解 等價於 @[email protected] 將返回值已json形式返回
到這一個簡單直觀的springboot專案就完事兒了,並且通過一個sayHello模擬了一個http請求