装配机制核心原理
Java AOP的装配本质是通过动态代理在运行时将通知(Advice)织入目标对象。Spring AOP提供两种代理方式:
- JDK动态代理:基于接口实现,要求目标类必须实现至少一个接口
- CGLIB代理:通过子类化实现,可代理未实现接口的普通类
关键装配组件
1. ProxyFactoryBean
最基础的编程式装配方式,配置灵活但稍显繁琐:
@Bean
public ProxyFactoryBean businessServiceProxy() {
ProxyFactoryBean factory = new ProxyFactoryBean();
factory.setTarget(new BusinessService());
factory.addAdvice(new LoggingAdvice());
return factory;
}
2. 自动代理创建器
更现代的声明式装配方式,主要包括:
- BeanNameAutoProxyCreator:根据Bean名称自动创建代理
- DefaultAdvisorAutoProxyCreator:基于Advisor自动代理(最常用)
完整示例:方法执行日志切面
定义切面类
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("执行方法: " + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))",
returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("方法返回: " + result);
}
}
启用自动代理
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.example")
public class AppConfig {
// 自动代理已通过注解启用
}
业务类
@Service
public class UserService {
public String getUserById(Long id) {
return "用户" + id;
}
}
测试验证
public class Application {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
userService.getUserById(1L);
}
}
输出结果:
执行方法: getUserById
方法返回: 用户1
总结
通过自动代理机制,Spring AOP实现了非侵入式的功能增强,使开发者能够专注于核心业务逻辑。现代Spring Boot项目中只需使用@EnableAspectJAutoProxy配合@Aspect注解即可轻松装配切面,大大提升了代码的可维护性和架构的灵活性。

被折叠的 条评论
为什么被折叠?



