(一)spring boot 不繼承parent搭建環境-入門
阿新 • • 發佈:2019-02-18
最近spring boot較火,抽空學習了一下,但是看教程需要通過繼承的方式搭建,折騰了半天搭了一個不用繼承parent的版本
- 環境準備工作:採用eclipse+maven來構建
-
jdk:1.7
- maven:3.3.9
1 新建一個maven專案
1.1新建一個maven專案:
1.2 選擇一個web專案
1.3 設定名稱
1.4 建立好專案後目錄結構如下:
2 引入spring boot
2.1編輯pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dtf</groupId>
<artifactId>spring-boot-test-1</artifactId>
<packaging> jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-test-1 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId >spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<!--ImportdependencymanagementfromSpringBoot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.4.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-boot-test-1</finalName>
</build>
</project>
儲存檔案後maven=>update project
注意:由於開始我是新建的一個web型別的專案所以,這裡war要改為jar
2.2 新建一個Application.java檔案到com.dtf目錄下
檔名隨意,但是這個檔案必須放在所有Controller的上一級包下,否則報404,這裡掃描Controller的註解是根據main方法中的SpringApplication.run(Application.class, args); Application這個類的路徑來掃描註解
package com.dtf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
到此可以啟動一下,試試能不能啟動,如果出現如下提示,恭喜你,引入jar包什麼的,沒有問題了~
2.3建立第一個Controller
package com.dtf.web;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping(value="/index")
@RestController
public class IndexController {
@RequestMapping
public String hi() {
return "hi";
}
@RequestMapping(value="/hi")
public String sayHi(@RequestParam String name){
return "hi,"+name;
}
@RequestMapping(value="/getMap/{name}")
public Map getMap(@PathVariable String name){
Map map = new HashMap();
map.put("name", name);
return map;
}
}
3.測試
3.1直接訪問
3.2帶引數訪問
3.3通過路徑方式帶參訪問
Spring boot 第一個專案就這麼簡單的就啟動了,並且在過程中並沒有配置哪怕一個mvc的xml
具體見附件