Spring AOP通过@DeclareParents注解为对象新增方法

场景分析

使用@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.			// 强制转换中执行

Reference

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jaemon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值