@DeclareParents 注解实现接口功能增强:Spring中通过接口引入实现功能增强的完整示例
以下是Spring中通过接口引入实现功能增强的完整示例:
// 1. 目标接口及实现类
package com.example;
public interface Service {
void doSomething();
}
@Component
class ServiceImp implements Service {
@Override
public void doSomething() {
System.out.println("执行核心业务逻辑");
}
}
// 2. 要引入的新接口
package com.example;
public interface AuditLog {
void logAuditInfo();
}
// 3. 切面实现类
package com.example;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AuditAspect {
// 使用@DeclareParents声明引入关系
@DeclareParents(
value = "com.example.ServiceImp", // 目标bean
defaultImpl = AuditLogImpl.class // 实现类
)
private AuditLog auditLog; // 引入的接口类型
// 定义接口实现类
private static class AuditLogImpl implements AuditLog {
@Override
public void logAuditInfo() {
System.out.println("记录审计日志信息");
}
}
}
// 4. Spring配置类
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
@Bean
public ServiceImp serviceImp() {
return new ServiceImp();
}
}
// 5. 测试类
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
Service service = context.getBean(ServiceImp.class);
// 强转为引入的接口
AuditLog auditLog = (AuditLog) service;
service.doSomething(); // 执行原有功能
auditLog.logAuditInfo(); // 调用增强功能
}
}
输出结果:
执行核心业务逻辑
记录审计日志信息
关键点总结表格:
特性 | 说明 |
---|---|
@DeclareParents | 声明接口引入关系,通过value 指定目标bean,defaultImpl 指定实现类 |
接口实现类 | 需要作为内部类或静态类实现引入的接口 |
动态类型转换 | 目标bean在运行时会自动具备引入接口的类型,可通过强制类型转换调用方法 |
作用范围 | 仅对声明时指定的bean生效 |
依赖配置 | 需要开启AOP代理(@EnableAspectJAutoProxy ) |
该方案通过AOP的接口引入机制,在不修改原有代码结构的前提下,实现了:
- 功能增强的解耦
- 接口实现的动态绑定
- 代码的横向扩展能力
- 更清晰的模块化边界