tomcat 8.5+
java8+
Maven3.2+
Gradle4+
看官網說明
使用Maven只要使用簡單的專案即可
※Maven 設定
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
※
※Gradle 設定
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'sbt'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter'
testCompile 'org.springframework.boot:spring-boot-starter-test'
compile 'org.springframework.boot:spring-boot-starter-web'
}
※
※Controller
package ooo.xxx;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Component
@RequestMapping("/testSpringBoot")
public class HelloSpringBoot {
@RequestMapping("/helloWorld")
@ResponseBody
public Map<String, String> displayHelloWorld() {
Map<String, String> map = new HashMap<>();
map.put("a", "aaa");
map.put("b", "bbb");
return map;
}
}
※
※測試
package ooo.xxx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Test {
public static void main(String[] args) {
SpringApplication.run(Test.class, args);
}
}
※小心 @SpringBootApplication 裡有個 @ComponentScan,預設只會掃瞄啟動類和他的子類,否則運行起來時不報錯,但網頁會報錯,如下有四個 package:
ooo
ooo.zzz
ooo.xxx
ooo.xxx.zzz
測試類只有在 ooo 和 ooo.xxx 才會執行成功
如果一定要不同的 package,那就再加個 @ComponentScan
※網址打上 http://localhost:8080/testSpringBoot/helloWorld 可以看到 JSON
※如果不喜歡用 8080 可以在 classpath 增加一個檔案叫 application.properties 或application.yml,內容寫 server.port=9000 即可,但 yml 是玩空格玩得很厲害的檔案,可參考官網,但如果兩個檔案都寫是 properties 贏了


沒有留言:
張貼留言