一、创建一个简单的Maven项目
使用Maven
,通过导入Spring Boot
的starter
模块,可以将许多程序依赖的包自动导入到工程中。使用Maven
的parent POM
,还可以更加容易地管理依赖的版本和使用默认的配置,工程中的模块也可以很方便地继承它。
在pom.xml
中添加如下依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
二、创建一个Spring Boot应用
package com.lemon.springboot.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author lemon
*/
@SpringBootApplication
@RestController
public class Application {
@RequestMapping("/")
public String home() {
return "hello";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这个简单的实例,是Spring Boot
应用的一个入口,或者叫做主程序,其中使用的@SpringBootApplication
来标注它是一个Spring Boot
应用,main
方法使它成为一个主程序,将在应用启动的时候首先执行main
方法,其次@RestController
表明这个程序还是一个控制器,如果在浏览器中访问项目的根目录,它将返回字符串hello
。
三、启动项目
启动项目,也就是运行main
方法,在浏览器访问http://localhost:8080/
,即将看到页面上显示了hello
。其实在依赖中集成了Tomcat
,服务器服务由Tomcat
提供。