Spring Boot作爲微服務框架,已經越來越多的公司在使用,最近因爲公司有新項目要使用Spring Boot框架,所以打算學習一下,並做好筆記。Spring Boot項目一般都是跟Maven一起使用,當然也可以使用Ant。接下來的學習中主要還是使用Maven來作爲jar包依賴管理。Maven的配置可參考本人另一篇博客:http://blog.csdn.net/polo_longsan/article/details/53749760。去Spring官網可以下載,Spring Boot的示例https://start.spring.io/。下面簡單搭建Spring boot的一個小示例。
1、新建maven項目,pom.xml配置如下:
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter</artifactId> -->
<!-- </dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、新建一個java類,作爲應用的主入口
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
public class Main {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
}
3、執行main方法,在瀏覽器中訪問web應用;http://localhost:8080/
瀏覽器輸出hello world!
說明:
pom.xml中spring-boot-starter-parent中已經引入了一些必須依賴,包括Tomcat插件,Spring,Spring MVC等一些依賴。要使用Spring Boot,需要Spring 4.0及以上版本,jdk需要1.8版本。其中引用注入口中@EnableAutoConfiguration會自動注入應用配置。