Annotation + AOP

Requirement: 在目标方法invoke 之前进行validation,通过就proceed.不通过就throw exception.
@Validation(validationRule=***)
public submit(Order order){}

Approach:

BeanPostProcessor 处理有Annotaion 的bean, 加入所需要的Advice 和PointCut,
当然不可以没有MethodInterceptor,(在这里处理Business Validation Logic),(MethodBeforeAdvice, AfterReturningAdvice不够适合)
在Java中,自定义注解(Annotation)是一种元数据,用于在代码中提供附加信息,而这些信息通常不会直接影响程序的执行。自定义注解实体类是一种用户创建的注解类型,它包含一个或多个字段,这些字段可以存储额外的数据。 要创建一个自定义注解,你需要按照以下步骤操作: 1. 定义注解类:创建一个新的Java接口,添加你想要的属性(@Retention, @Target, 或者你自己定义的字段),例如: ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) // 表示注解在运行时可用 @Target(ElementType.METHOD) // 指定注解可以应用在方法上 public @interface MyCustomAnnotation { String value(); int priority() default 0; } ``` 这里定义了一个名为`MyCustomAnnotation`的注解,有两个属性:`value`和`priority`。 2. 在目标类中使用注解:在需要应用注解的方法上添加注解,例如: ```java public class MyClass { @MyCustomAnnotation(value = "Important Method", priority = 1) public void myMethod() { // 方法体... } } ``` 3. AOP(面向切面编程)与自定义注解:Spring AOP或AspectJ等工具可以让你在运行时扫描并处理带有特定注解的方法。你可以编写一个切面(Aspect),使用`@Around`, `@Before`, 或 `@After` 等通知处理`@MyCustomAnnotation`注解的方法。例如,你可能想在方法执行前后执行一些额外的操作,或者根据`priority`属性决定是否执行某些操作。 ```java @Aspect @Component public class MyAspect { @Around("@annotation(myCustomAnnotation)") public Object advice(ProceedingJoinPoint joinPoint, MyCustomAnnotation myCustomAnnotation) throws Throwable { System.out.println("Before executing method with priority: " + myCustomAnnotation.priority); Object result = joinPoint.proceed(); System.out.println("After executing method with priority: " + myCustomAnnotation.priority); return result; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值