Spring Boot

前端后端都被host在web服务器上,都可用http请求访问
前端项目被访问则返回html/js等
后端项目被访问则返回json等


Annotations:

@SpringBootApplication:

mark the main class of a Spring Boot application

API Layer:

@RestController

@RequestMapping

@GetMapping

Generally we use @Controller annotation with @RequestMapping annotation to map HTTP requests with methods inside a controller class.

//Java program to demonstrate @RequestMapping annotation
@RestController
public class MyController{
  @RequestMapping(value=" ",method=RequestMapping.GET)
  public String GFG(){
    //insert code here
  }
}
//@RequestMapping 可以用在类级别。通常用于定义一个控制器的基本请求映射,以便将类中的所有方法的请求路径集中管理。
@RestController
@RequestMapping
public class MyController{
  @GetMapping
  public String GFG(){
    //insert code here
  }
}

Business Layer:

@Service

@Service
public class StudentService {
    public int getAge(){
        //interact with data
    }
}

Dependency Injection

@Autowired

此例中StudentService是被手动实例化的,不推荐。

@RestController
@RequestMapping(value = "/api/v1")
public class StudentController {
    private final StudentService studentService;
    public StudentController() {
        this.studentService = new StudentService();
    }
    @GetMapping("/age")
    public int age(){
        return studentService.age();
    }
}

推荐写法为Dependency Injection,StudentService被@Autowired自动实例化并注入。

@RestController
@RequestMapping(value = "/api/v1")
public class StudentController {
    private final StudentService studentService;
    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }
    @GetMapping("/age")
    public int age(){
        return studentService.age();
    }
}


在 Spring 启动时,容器会扫描被标记为 Spring bean 的类(例如用
@Component@Service@Repository@Controller 注解的类),并创建它们的实例。



@Service 完成了 StudentService 的实例化。@Autowired 完成了将 StudentService 的实例注入到 StudentController 中。这两者共同协作,实现了 Spring 的依赖注入机制。


N-Tier Architecture