1、在eclipse中创建maven简单(quick)应用:
接下来输入group id和artifact id。。。
2、在pom文件中引入spring-boot:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</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>
3、编写controller:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class Test {
@RequestMapping("test")
@ResponseBody
public String home() {
return "Hello World!";
}
}
4、编写启动类:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
接下来启动App.java主类,就完成了web项目搭建。不需要web.xml,不需要配置文件、也不需要tomcat容器。在浏览器上输入:http://localhost:8080/test 即可。
可能会遇到的问题:
1)Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletCont
这个问题很诡异,我按照网上的做法在pom.xml中加入了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
图同时在App主类上加上@EnableAutoConfiguration注解,再次启动就好了。但是后面我又把这两个改动删除了,启动也不会报错了。
2)This application has no explicit mapping for /error, so you are seeing this as a fallback.
在浏览器上输入http://localhost:8080/test 显示如下错误,主要因为:
A、检查SpringbootApplication的位置是否直接在groupId的包下面 ,比如你的groupId是com.baidu。那么SpringbootApplication放在\src\main\java\com\baidu\目录下 ,spring-boot会自动扫描包下所有的文件。
B、如果第一步并且使用的是thymeleaf模板引擎,那么再检查有没有添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
C、App主类上没有加:@SpringBootApplication 注解。(我就是这种原因)