文章目录
前言
本笔记系统整理了Java后端开发中的核心知识点,涵盖分层架构设计、注解原理与面向对象核心概念,帮助开发者构建高内聚低耦合的健壮系统。
一、代码开发分层架构
在sky-server
项目中采用标准三层架构:
// Controller层:接收请求和返回响应
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/status/{status}")
public Result setStatus(@PathVariable Integer status, Long id) {
employeeService.updateStatus(id, status);
return Result.success();
}
}
// Service层:处理业务逻辑
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
@Override
public void updateStatus(Long id, Integer status) {
Employee employee = Employee.builder()
.id(id)
.status(status)
.build();
employeeMapper.update(employee);
}
}
// Mapper层:数据访问
@Mapper
public interface EmployeeMapper {
void update(Employee employee);
}
二、注解详解
1. 编译器级注解
@Override // 强制检查方法重写正确性
public void print() {
System.out.println("子类实现");
}
- 核心作用:为编译器提供元数据,实现静态检查
- 反射机制:运行时可通过反射获取注解信息
Annotation[] annotations = method.getAnnotations();
for (Annotation ann : annotations) {
if (ann instanceof Override) {
System.out.println("检测到Override注解");
}
}
2. 架构设计原则
- 高内聚:类的内部操作自主完成,拒绝外部干涉
- 低耦合:仅暴露必要方法,降低模块间依赖
- 示例:
// 高内聚:封装内部状态
public class Account {
private double balance;
// 低耦合:仅暴露安全操作方法
public synchronized void deposit(double amount) {
validateAmount(amount);
this.balance += amount;
}
private void validateAmount(double amount) {
if (amount < 0) throw new IllegalArgumentException();
}
}
三、面向对象核心概念
1. 继承机制
- 查看继承关系:
Ctrl+H
打开继承树 - 根类继承:所有类默认继承
Object
- protected权限:允许子类访问父类受保护成员
public class Person {
protected String name; // 子类可访问
}
2. 方法重写(Override)
class Person {
public void print() {
System.out.println("父类方法");
}
}
class Student extends Person {
@Override // 重写父类方法
public void print() {
super.print(); // 调用父类实现
System.out.println("子类扩展");
}
}
3. 构造器调用规则
特性 | 说明 |
---|---|
隐式super() | 子类构造器首行自动调用父类无参构造 |
私有成员不可继承 | 父类private字段/方法对子类不可见 |
调用顺序 | 父类构造器 → 子类构造器 |
public class Person {
public Person() {
System.out.println("Person构造器");
}
}
public class Student extends Person {
public Student() {
// 编译器自动添加super();
System.out.println("Student构造器");
}
}
/* 输出:
Person构造器
Student构造器
*/
4. 内存继承模型
总结
核心要点回顾:
- 分层架构实现职责分离:Controller→Service→Mapper
- 注解提供元数据编程能力,支撑框架设计
- 面向对象三大支柱:
- 封装:通过访问控制实现高内聚
- 继承:
protected
支持子类扩展 - 多态:方法重写实现运行时绑定
如果内容对您有帮助,请点赞👍、关注❤️、收藏⭐️。创作不易,您的支持是我持续创作的动力!