场景分析
使用@DeclareParents
注解为实现类SoloService和KafkaService添加新方法ICommonService.valid方法。
实战案例
接口层
package com.jaemon.service;
public interface IConsensusService {
void consensus();
}
实现类
package com.jaemon.service.impl;
@Slf4j
@Service
public class SoloService implements IConsensusService {
@Override
public void consensus() {
log.info("solo consensus execute...");
}
}
@Slf4j
@Service
public class KafkaService implements IConsensusService {
@Override
public void consensus() {
log.info("kafka orderer execute...");
}
}
待添加的公共方法
package com.jaemon.common;
public interface ICommonService {
void valid();
}
@Slf4j
@Service("commonService")
public class CommonServiceImpl implements ICommonService {
@Override
public void valid() {
log.info("common valid execute.");
}
}
AOP配置
package com.jaemon.aop;
@Component
@Aspect
@Slf4j
public class RequestAop {
// 为com.jaemon.service.impl下的所有类对象实例添加commonService中的方法
@DeclareParents(value="com.jaemon.service.impl.*", defaultImpl= CommonServiceImpl.class)
public static ICommonService commonService;
}
接口测试
@RestController
@Slf4j
public class HashController {
@Autowired
private IConsensusService soloService;
@Autowired
private IConsensusService kafkaService;
@GetMapping("/execute")
public Response execute() {
soloService.consensus();
// 强制转换
ICommonService commonService1 = (ICommonService) soloService;
commonService1.valid();
log.info("");
kafkaService.consensus();
// 强制转换
ICommonService commonService2 = (ICommonService) kafkaService;
commonService2.valid();
return Response.success();
}
}
日志输出
solo consensus execute...
common valid execute.
kafka orderer execute...
common valid execute.
添加前置执行AOP
package com.jaemon.aop;
@Aspect
public class CommonPointcuts {
@Pointcut("execution(* com.jaemon.service.*.*(..))")
public void businessService() {}
}
@Component
@Aspect
@Slf4j
public class RequestAop {
@DeclareParents(value="com.jaemon.service.impl.*", defaultImpl= CommonServiceImpl.class)
public static ICommonService commonService;
@Before("com.jaemon.CommonPointcuts.businessService() && this(commonService)")
public void executeValid(ICommonService commonService) {
commonService.valid();
}
}
日志输出
common valid execute. // AOP @Before中执行
solo consensus execute...
common valid execute. // 强制转换中执行
common valid execute. // AOP @Before中执行
kafka orderer execute...
common valid execute. // 强制转换中执行