SpringBoot认识

之所以接触SpringBoot并学习它,主要是因为他可以来简化 Spring 应用的初始搭建以及开发过程,想想之前不管你是搭建SSH还是SSM最头痛的莫过于是要创建一大堆繁琐的配置文件,使用
SpringBoot就不用了,使用Spring boot,可以轻松的创建独立运行的程序,非常容易构建独立的服务组件,是实现分布式架构、微服务架构利器。Spring boot简化了第三方包的引用,通过提供的starter,简化了依赖包的配置。

搭建一个springBoot 应用

废话不多说,既然SpringBoot有这么多优点那我们就来搭建一个SpringBoot环境吧,首先Spring Boot提供了一系列的依赖包,所以需要构建工具的支持,这里我使用Maven构建工具

1.创建一个普通的maven工程

2.在pom.xml中添加SpringBoot的依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/><!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>

<dependencies>
<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.创建目录和配置文件

在maven工程的src/main/resource目录下创建templates目录、static目录和application.properties三个文件
其中
templates目录:存放模板文件
static目录:存放css、js等静态文件
application.properties:这个文件配置项目运行所需数据

4.创建启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.xueliang;  

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
public class MySpringBootDemo {
public static void main(String[] args) {
//项目入口
SpringApplication.run(MySpringBootDemo.class, args);

}
}

5.测试

写一个Controller跳转 注意: 所有代码文件必须放在启动类所在包下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.xueliang.controller;  

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
/**
* 返回基本类型 json数据格式
* @return
*/
@RequestMapping("hello")
public String showHello(){
return "hello Springboot";
}
}

至此一个springBoot应用已经搭建成功