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
- Presentation Layer(表示层/控制层):负责接收用户请求和返回响应,处理客户端的输入输出。在Web应用中,这一层通常由控制器(如Spring中的
Controller
或RestController
)组成。
- Business Layer(业务层):处理业务逻辑,是应用的核心。它执行业务规则和流程,调用数据层来存取数据。业务层通常由服务类(如Spring中的
Service
)组成。
- Data Access Layer(数据访问层/持久层):负责与数据库进行交互,执行CRUD操作。这一层通常由数据访问对象(DAO)或存储库(Repository)组成。
- Database(数据库):存储实际的数据,是应用的数据持久化存储。