1.新建maven工程
2.在pom中设parent 为 spring-boot-starter-parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
3.添加应用需要的starter模块,作为示例,我们仅添加web starter模块。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
4.写一个简单的 Controller
package cn.larry.spring.controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
这里有两个新东西:@EnableAutoConfiguration 和 SpringApplication 。
@EnableAutoConfiguration 用于自动配置。简单的说,它会根据你的pom配置(实际上应该是根据具体的依赖)来判断这是一个什么应用,并创建相应的环境。
在上面这个例子中,@EnableAutoConfiguration 会判断出这是一个web应用,所以会创建相应的web环境。
SpringApplication 则是用于从main方法启动Spring应用的类。默认,它会执行以下步骤:
- 创建一个合适的ApplicationContext实例 (取决于classpath)。
- 注册一个CommandLinePropertySource,以便将命令行参数作为Spring properties。
- 刷新application context,加载所有单例beans。
- 激活所有CommandLineRunner beans。
⑤ 现在,直接右键启动main方法即可。
⑥ 默认访问地址: http://localhost:8080/
7.我们也可以设置自己的项目路径 -- 在classpath下的 application.properties 或者 application.yaml 文件中设置即可。
# application.yaml
# Server settings (ServerProperties)
server:
port: 8080
address: 127.0.0.1
sessionTimeout: 30
contextPath: /aaa
# Tomcat specifics
tomcat:
accessLogEnabled: false
protocolHeader: x-forwarded-proto
remoteIpHeader: x-forwarded-for
basedir:
backgroundProcessorDelay: 30 # secs
# application.properties
# Server settings (ServerProperties)
server.port=8080
server.address=127.0.0.1
#server.sessionTimeout=30
server.contextPath=/aaa
# Tomcat specifics
#server.tomcat.accessLogEnabled=false
server.tomcat.protocolHeader=x-forwarded-proto
server.tomcat.remoteIpHeader=x-forwarded-for
server.tomcat.basedir=
server.tomcat.backgroundProcessorDelay=30
server.contextPath 为本服务访问要加上的路径 即访问为http://localhost:8080/aaa/