SpringBoot学习之入门学习笔记

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。我在此做一些学习笔记,以便今后用到时可以迅速搭建开发环境。

开发环境的搭建

搭建开发环境首先需要安装IDEAhttps://www.jetbrains.com/idea/。安装完成后就可以创建SpringBoot项目:
Create New Project -> Spring Initializr -> 选择JDK -> Next -> 选择dependence(勾选web) -> finish。
创建好工程以后,工程中有一个默认的DemoApplication:

1
2
3
4
5
6
7
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

Web服务器开始工作,返回Hello World

这个Application执行起来并没有任何效果,要让SpringBoot响应网络请求,可以定义一些Controller类,例如:

1
2
3
4
5
6
7
8
@RestController
public class HelloController {

@GetMapping("hello")
public String printHello() {
return "Hello World!!";
}
}

这时在执行程序,并在浏览器中输入:http://localhost:8080/hello 就可以返回Hello World了。(默认端口号8080)

创建RestApi,返回JSON数据

很多情况下我们用SpringBoot来做接口服务器,需要返回Json数据,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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@RestController
public class ManController {

@GetMapping("man")
public Man getMan() {
return new Man("xiaoli", 25);
}

@GetMapping("men")
public List<Man> getManList() {
List<Man> men = new ArrayList<>();
men.add(new Man("qiwei", 25));
men.add(new Man("dingding", 26));
return men;
}

public static class Man {
private String name;
private int age;

public Man(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}
}

这是侯访问接口:http://localhost:8080/man 返回json数据:
1
2
3
4
{
name: "xiaoli",
age: 25
}

访问接口:http://localhost:8080/men 返回list数据:

1
2
3
4
5
6
7
8
9
10
[
{
name: "qiwei",
age: 25
},
{
name: "dingding",
age: 26
}
]

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器