Spring Boot 学习笔记
学习代码第一步:如何写 Hello world ?
1、新建项目
新建一个 Maven Java 工程,在 pom.xml 文件中添加 Spring Boot Maven 依赖:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.1.6</version> </parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin </artifactId> </plugin> </plugins> </build>
2、创建启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
3、创建HelloController
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/")
public String hello(){
return "Hello world!!";
}
}
4、启动
运行App的Main函数,之后打开浏览器输入地址:http://127.0.0.1:8080/ 就可以看到 Hello world!了。
5、返回JSON数据
5.1、编写一个实体类Demo
package org.example.bean;
public class Demo {
private long id ;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
5.2、编写 DemoController
在 DemoController 加上@RestController 和@RequestMapping 注解;
package org.example.web;
import org.example.bean.Demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/getDemo")
public Demo getDemo(){
Demo demo = new Demo();
demo.setId(1L);
demo.setName("风萧萧1999");
return demo;
}
}
5.3、测试
那么在浏览器访问地址:http://127.0.0.1:8080/demo/getDemo 返回如下数据: