首先我们来看下springboot的基本目录结构。
1. 创建maven工程并引入相关依赖
<!--相当于引入父类依赖库,通过指定其version,<dependency>标签中的
version可以省略,极大减少开发难度。-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
</parent>
<!--引入web模块,不用再像SpringMVC那样写大量配置文件-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2. 编写一个主程序,用来作为启动入口
package com.yhr.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run =
SpringApplication.run(MainApplication.class, args);
}
}
通过源码发现SpringBootApplication
注解由三个元注解组合而成,@ComponentScan
注解扫描主程序所在包下的所有bean,相当于标签<context:component-scan>
。
可以通过SpringBootApplication
的scanBasePackages
,修改扫描的包。
3. 编写一个配置类
配置类的作用相当于配置文件
package com.yhr.boot.config;
import com.yhr.boot.bean.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//此为配置类
@Configuration
public class MyConfig {
@Bean
public Student student01(){//依赖了Cat组件
Student student = new Student(21, "yhr");
return student;
4. 编写实体类Student
package com.yhr.boot.bean;
public class Student {
private int sno;
private String sname;
public Student() {
}
public Student(int sno, String sname) {
this.sno = sno;
this.sname = sname;
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
@Override
public String toString() {
return "Student{" +
"sno=" + sno +
", sname='" + sname + '\'' +
'}';
}
}
5. controller层
package com.yhr.boot.controller;
import com.yhr.boot.bean.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//@ResponseBody
//@Controller
@Slf4j//日志
@RestController
public class HelloController {
@Autowired
Student student;
@RequestMapping("/hello")
public Student handle01(){
return student;
}
通过源码发现@RestController
就是@ResponseBody
和@Controller
的结合,因此写一个大的即可。
6. 测试
由于springboot帮我们完成了tomcat的部署,直接运行启动类即可。
出现这样就代表启动成功。直接在浏览器地址栏输入http://localhost:8080/hello
即可,我的端口号是8080,根据大家的端口号修改即可。
浏览器默认显示json数据格式的数据。完成!