代理对象中存在target属性
因为代理对象没有进行依赖注入,获取到的代理对象,代理对象中的属性没有赋值
当执行到方法内部后,即进入对象中方法时,则属性不为空了。因为执行到内部,实际是执行了target.xxx(),此刻已经是原始对象,而不再是代理对象.

利用cglib进行AOP的大致流程

  1. 1. 生成代理类UserServiceProxy,代理类继承UserService
  2. 2. 代理类中重写了父类的方法,比如UserService中的test()方法
  3. 3. **代理类中还会有一个target属性**,该属性的值为被代理对象(也就是通过UserService类推断构造方法实例化出来的对象,进行了依赖注入、初始化等步骤的对象)
  4. 4. 代理类中的test()方法被执行时的逻辑如下:
  5. 1. 执行切面逻辑(@Before
  6. 2. 调用target.test()
  7. 3. 执行切面逻辑(@After

验证target属性存在

1.定义SenderConfig注解
2.SendConfigAspect服务利用切面,对使用@SenderConfig注解的方法进行后置处理
3.在WafSecurityPolicyServiceImpl服务方法使用@SenderConfig注解
4.测试效果

  1. /**
  2. * 标记配置文件发送mq
  3. */
  4. @Target({ ElementType.METHOD })
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @Documented
  7. @Inherited
  8. public @interface SenderConfig {
  9. String tableName() default "";
  10. String operate() default"";
  11. }
  12. @Aspect
  13. @Component
  14. @Slf4j
  15. public class SendConfigAspect {
  16. @Autowired
  17. private RabbitSender rabbitSender;
  18. @AfterReturning(value = "@annotation(senderConfig)", returning = "result")
  19. public void doAroundMethod(JoinPoint joinPoint, SenderConfig senderConfig, Object result) {
  20. log.info("{}表,{}操作,配置信息同步", senderConfig.tableName(), senderConfig.operate());
  21. ConfigTypeEnum configTypeEnum = ConfigTypeEnum.forName(senderConfig.tableName());
  22. ActionTypeEnum actionTypeEnum = ActionTypeEnum.forDesc(senderConfig.operate());
  23. Object o = joinPoint.getArgs()[0];
  24. if (o != null && configTypeEnum != null && actionTypeEnum != null) {
  25. Content<Object> content = Content.builder()
  26. .configType(configTypeEnum.value())
  27. .actionType(actionTypeEnum.value())
  28. .configContent(hump2Underline(o))
  29. .build();
  30. String finalJson = hump2Underline(content);
  31. rabbitSender.send(finalJson);
  32. log.info("配置信息同步成功:{}", finalJson);
  33. }
  34. }
  35. /**
  36. * 将驼峰转换成下划线,进行json序列化
  37. *
  38. * @param content 原驼峰实例对象
  39. * @return 下划线json字符串
  40. */
  41. private String hump2Underline(Object content) {
  42. SerializeConfig config = new SerializeConfig();
  43. config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
  44. return JSON.toJSONString(content, config);
  45. }
  46. @Slf4j
  47. @Service
  48. public class WafSecurityPolicyServiceImpl implements WafSecurityPolicyService {
  49. @Resource
  50. private WafPolicyMapper wafPolicyMapper;
  51. @Override
  52. @SenderConfig(tableName = "ctwaf_policy", operate = "新增")
  53. public int addSecurityPolicy(WafSecurityPolicyDto wafSecurityPolicyDto) {
  54. WafPolicyDO wafPolicyDO = new WafPolicyDO();
  55. BeanUtils.copyProperties(wafSecurityPolicyDto, wafPolicyDO);
  56. wafPolicyDO.setCreateTime(new Date());
  57. wafPolicyDO.setUpdateTime(new Date());
  58. return wafPolicyMapper.insert(wafPolicyDO);
  59. }
  60. }

image.png
图一,验证AOP中代理对象中存在target属性存在,且target为被代理对象,代理对象中wafPolicyMapper属性没有进行属性注入。
image.png
当执行到具体方法中时,代理对象执行target.addSecuritryPolicy,所以图二展示的是实际对象调用效果