使用 spring boot 有什麼好處
- 其實就是簡單、快速、方便!平時如果我們需要搭建一個 spring web 項目的時候需要怎麼做呢?
- 配置 web.xml,加載 spring 和 spring mvc
- 配置數據庫連接、配置 spring 事務
- 配置加載配置文件的讀取,開啓註解
- 配置日誌文件
- …
配置完成之後部署 tomcat 調試,現在非常流行微服務,如果我這個項目僅僅只是需要發送一個郵件,或者我的項目僅僅是生產一個積分,我都需要這樣折騰一遍,想想就很累!
快速入門
maven 構建項目
- 訪問 http://start.spring.io/
- 選擇構建工具 Maven Project、Spring Boot 版本以及一些工程基本信息,點擊“ Switch to the full version. ”,可以看到更多的配置
- 點擊 Generate Project 下載項目壓縮包
- 解壓後,使用 eclipse,Import -> Existing Maven Projects -> Next ->選擇解壓後的文件夾-> Finsh,OK done!
項目結構介紹
spingboot 建議的目錄結果如下:
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
+- service
| +- CustomerService.java
+- controller
| +- CustomerController.java
Application.java 建議放到根目錄下面,主要用於做一些框架配置
domain 目錄主要用於實體(Entity)與數據訪問層(Repository)
service 層主要是業務類代碼
controller 負責頁面訪問控制
採用默認配置可以省去很多配置,當然也可以根據自己的喜歡來進行更改最後,啓動 main 方法,至此一個項目搭建好了!
官方的構建工具非常舒服,下面我選擇自己創建一個maven項目,自己做配置,我的項目結構如下:
引入web模塊
1.pom.xml 中添加支持 web 的模塊:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springboot</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
2.編寫 controller 內容:
package com.bdqn.zmj.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HellController {
@RequestMapping("/hello")
public String index() {
return "Hello World";
}
}
@RestController 的意思就是 controller 裏面的方法都以 json 格式輸出
3.啓動類
package com.bdqn.zmj.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.bdqn.zmj")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
3、啓動 main 方法,打開瀏覽器訪問 http://localhost:8080/hello 就可以看到效果了!