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会自动注入应用配置。