学习进度条4.7
所花时间:6小时
代码量:200
搏客量:2
了解到的知识点:
在 Spring Boot 中,耦合是一个重要的概念,涉及到代码的可维护性、可扩展性和模块化设计。以下是关于 Spring Boot 中耦合的一些知识点:
-
依赖注入(Dependency Injection, DI)
作用:通过依赖注入,可以降低类之间的耦合度。Spring Boot 使用依赖注入来管理 Bean 的生命周期和依赖关系。
实现方式:
使用 @Autowired 注解自动装配依赖。
使用构造函数注入或 setter 方法注入。
@Service
public class UserService {
private final UserRepository userRepository;// 构造函数注入,降低耦合
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
} -
面向接口编程
作用:通过定义接口,将实现细节与接口解耦,便于后续扩展和维护。
public interface UserRepository {
User findById(Long id);
}
@Repository
public class UserRepositoryImpl implements UserRepository {
@Override
public User findById(Long id) {
// 实现逻辑
}
}
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
3. AOP(面向切面编程)
作用:通过 AOP 将横切关注点(如日志、事务、安全等)从业务逻辑中分离出来,降低耦合。
实现方式:
使用 @Aspect 和 @Around、@Before、@After 等注解。
@Aspect
@Component
public class LoggingAspect {
@Around("execution(* com.example.service..(..))")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long end = System.currentTimeMillis();
System.out.println("Method execution time: " + (end - start));
return result;
}
}
4. 事件驱动(Event-Driven Architecture)
作用:通过事件发布和订阅机制,解耦模块之间的直接依赖。
实现方式:
使用 ApplicationEvent 和 ApplicationListener。
// 定义事件
public class UserCreatedEvent extends ApplicationEvent {
public UserCreatedEvent(User user) {
super(user);
}
}
// 发布事件
@Service
public class UserService {
@Autowired
private ApplicationEventPublisher publisher;
public void createUser(User user) {
// 业务逻辑
publisher.publishEvent(new UserCreatedEvent(user));
}
}
// 监听事件
@Component
public class UserCreatedListener implements ApplicationListener
@Override
public void onApplicationEvent(UserCreatedEvent event) {
// 处理事件
}
}

浙公网安备 33010602011771号