準備:
eclipse 首先創建一個maven項目。這裏不介紹。可以百度。
idea會更簡單一些。
開搞:
1. 引入相關依賴:https://mvnrepository.com (可以上這個網站上搜索)
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
說明一下: 其中spring-boot-starter 是spring-boot 自啓動的核心。 他依賴於 spring-boot 。 spring-boot-starter-web 依賴於spring-boot-starter 所以有些文章只寫一個 spring-boot-starter-web 也能成功。
2. 編寫啓動類
package com.springboot.mvc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* Hello world!
*
*/
@SpringBootApplication
//掃描包需要自行制定修改。否則會404
@ComponentScan("com.springboot.mvc")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class);
}
}
3.編寫控制層
package com.springboot.mvc.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("test")
public class TestController {
private Logger logger = LoggerFactory.getLogger(TestController.class);
@RequestMapping("check")
public String checkAlive(){
logger.info("you are right");
return "hello world";
}
}
4.啓動項目
啓動項第一個和第二個都是一個意思。
5.check
http://localhost:8080/test/check
可能出現的問題:
1.maven 依賴下不來, maven setting.xml 中添加入阿里雲鏡像
<mirrors>
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
2.maven 強烈建議自己下載一個不要用eclipse自帶的。