获取汽车的数据
1.创建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);
}
}
2.application.yml修改端口号
server:
port: 8090
3.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;
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;
}
@Override
public String toString() {
return "Car{" +
"id=" + id +
", name='" + name + '\'' +
", color='" + color + '\'' +
", price=" + price +
'}';
}
}
4.接口,定义抽象方法
package cn.tedu.service;
import cn.tedu.pojo.Car;
import java.util.List;
//接口里都是抽象方法
//jdk1.8也是可以有static或者defaul的普通方法
public interface CarService {
//简写形式,public abstact
List<Car> get();//获取Car数据
}
5.实现类,抽象方法重写
package cn.tedu.service;
import cn.tedu.pojo.Car;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
//实现类实现了接口要重写抽象方法,否则就是一个抽象类
@Service//和ComServiceImp一样,都可以完成ioc,只是更好的表示了
public class CarServicImp 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数据
}
}
6.接受请求
package cn.tedu.contorller;
import cn.tedu.pojo.Car;
import cn.tedu.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("car")
@CrossOrigin
public class CarComtroller {
//1.调用CarSeviceImp里准备好的汽车数据
@Autowired
private CarService carService;
//2.提供方法,给浏览器返回汽车数据
@RequestMapping("get")
public List<Car> get(){
//调用service的功能,service会把结果返回来
return carService.get();
}
}
7.结果展示
8.表结构