Spring Boot入門例子
阿新 • • 發佈:2019-01-28
首先使用Maven匯入必要的jar
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot</groupId>
<artifactId >springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding >
</properties>
<!-- Spring Boot 啟動父依賴 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies >
<!-- Spring Boot web依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
加入一個Controller
package cn.springboot.controller;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.springboot.dto.People;
@EnableAutoConfiguration
@RestController
public class HelloController {
@RequestMapping("/")
public String sayHello() {
return "Hello,World!";
}
@RequestMapping("/{id}")
public People getPeople(@PathVariable Integer id) {
People people = new People();
people.setId(id);
people.setAge("13");
people.setName("lisi");
return people;
}
}
- @RestController告訴Spring以字串的形式渲染結果,並直接返回給呼叫者。
- @EnableAutoConfiguration 。這個註解告訴Spring Boot根據新增的jar依賴猜測你想如何配置Spring。
一個啟動類
package cn.springboot.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import cn.springboot.controller.HelloController;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(HelloController.class, args);
}
}
我們的main方法通過呼叫run,將業務委託給了Spring Boot的SpringApplication類。SpringApplication將引導我們的應用,啟動Spring,相應地啟動被自動配置的Tomcat web伺服器。我們需要將 Example.class 作為引數傳遞給run方法來告訴SpringApplication誰是主要的Spring元件。為了暴露任何的命令列引數,args陣列也會被傳遞過去。
啟動後就可以進行訪問了
結果如下
參考
官方的《Spring Boot Reference Guide》