1.项目结构
2.RunApp启动类
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);
}
}
3.application.yml改端口
server:
port: 8090
4.Car类,封装数据
package cn.tedu.pojo;
import org.springframework.stereotype.Component;
//模型层,用来封装数据
@Component//交给spring框架进行ioc
public class Car {
private Integer id;
private String name;
private String color;
private Double price;
//get set tostring
@Override
public String toString() {
return "Car{" +
"id=" + id +
", name='" + name + '\'' +
", color='" + color + '\'' +
", price=" + price +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
5.CarService接口,定义抽象方法
package cn.tedu.service;
import cn.tedu.pojo.Car;
import java.util.List;
//接口里都是抽象方法
//jdk1.8也可以有static或者default的普通方法
public interface CarService {
//简写形式,public abstract
List<Car> get();//获取Car数据
}
6.CarServiceImpl实现类,重写抽象方法
package cn.tedu.service;
import cn.tedu.pojo.Car;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
//实现类实现了接口要重写抽象方法,否则就是一个抽象类
@Service//和Component一样,都可以完成ioc,只是更好的表示了是service层的代码
public class CarServiceImpl implements CarService{
//重写的要求:方法声明和父类一样,有权限
public List<Car> get(){
Car c1 = new Car();//空对象,属性都是默认值null
c1.setId(10);c1.setName("bmw");c1.setColor("red");c1.setPrice(9.9);
Car c2 = new Car();//空对象,属性都是默认值null
c2.setId(20);c2.setName("audi");c2.setColor("black");c2.setPrice(6.6);
List<Car> list = new ArrayList<>();
list.add(c1);
list.add(c2);
return list;//给调用者返回list数据
}
}
7.CarController,接受请求
package cn.tedu.controller;
import cn.tedu.pojo.Car;
import cn.tedu.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("car")
public class CarController {
//1,调用CarServiceImpl里准备好的汽车数据--DI
@Autowired
private CarService carService;
//2,提供方法,给浏览器返回汽车数据
@RequestMapping("get")
public List<Car> get(){
//调用service的功能,service会把结果返回来
return carService.get() ;
}
}
8.测试
9.总结