SpringBoot简单入门

今天学学springboot,springboot是spring4新出的,目的在于减少配置,加快开发速度,springboot中内嵌了tomcat等。
来看一个简单的hello world 的小demo。
著名的Hello World

新建一个maven项目

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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.lpj</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 继承springboot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<!-- 添加springWeb支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

我用的是目前比较新的版本,要求jdk1.8

下面我们来输出hello world

新建一个DemoController:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package 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;
/**
* @author lpj
* @date 2016年6月10日
*/
@Controller
@EnableAutoConfiguration
public class DemoController {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(DemoController.class, args);
}
}

@EnableAutoConfiguration是开启默认配置参数,就是之前我们pom中spring-boot-starter-parent自带的,tomcat也内嵌了,
所以直接run as Java Application,就ok了。如图
这里写图片描述

然后打开浏览器,输入localhost:8080,回车,就看到结果了

PS:

  • 在resource目录下,我们可以添加一个叫 banner.txt的文件,这样当项目启动的时候,会自动加载这个文件,在控制台输出banner.txt文件中的内容。当然,如果不想看到banner,也可以关闭,方法如下:
1
2
3
4
5
6
public static void main(String[] args) {
// SpringApplication.run(DemoController.class, args);
SpringApplication application = new SpringApplication(DemoController.class);
application.setShowBanner(false);
application.run(args);
}

或者使用链式语法:

1
2
3
4
5
6
7
public static void main(String[] args) {
// SpringApplication.run(DemoController.class, args);
// SpringApplication application = new SpringApplication(DemoController.class);
// application.setShowBanner(false);
// application.run(args);
new SpringApplicationBuilder().showBanner(false).sources(DemoController.class).run(args);
}

  • 有一点需要注意,如果run方法和controller分开放,项目入口文件【SpringApplication.run方法所在的那个类】所在的包名,必须要是controller,service,entity等等的包名的上级目录,否则会导致项目启动后无法正确显示显示页面。因为SpringApplication.run()启动时,会扫面同目录以及子目录下的@Controller,@Service,@Repository,@Componet等注解标识的类,如果不在目录不是父子关系,会识别不到,导致问题出现。