我的构建环境
JDK 8
Maven 3
Servlet3容器
创建项目
首先使用Maven创建一个普通Maven应用即可,不必是web的。
添加Spring Boot相关POM配置
在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.cw.spring-boot-demo</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
继承spring-boot-starter-parent后我们可以继承一些默认的依赖,这样就无需添加一堆相应的依赖,把依赖配置最小化;spring-boot-starter-web提供了对web的支持
(也可以增加spring-boot-maven-plugin提供了直接运行项目的插件,我们可以直接mvn spring-boot:run运行。)
控制器
运行
第一种方式
通过在DemoController中加上@EnableAutoConfiguration开启自动配置,然后通过SpringApplication.run(DemoController.class);运行这个控制器;这种方式只运行一个控制器比较方便;
第二种方式
通过@Configuration+@ComponentScan开启注解扫描并自动注册相应的注解Bean
第三种方式
通过@SpringBootApplication注解,实际属于第二种方式的封装
<span style="font-family: Helvetica, Tahoma, Arial, sans-serif; line-height: 25.2px;">package com.cw.controller;</span>
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
到此,一个基本的REST风格的web应用就构建完成了。运行Application.java
地址栏输入http://localhost:8080/hello/xxx
即可看到hello xxx结果。