要实现自定义注解和AOP(面向切面编程)在Spring Boot中的应用,可以通过自定义注解来标记需要进行AOP处理的方法,然后使用AOP来实现对这些方法的增强操作。
1. 创建自定义注解
首先创建一个自定义注解,用于标记需要进行AOP处理的方法。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
String value() default "";
}
2. 创建切面类
创建一个切面类,用于定义在被 CustomAnnotation 注解标记的方法上执行的增强操作。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class CustomAspect {
@Before("@annotation(com.example.CustomAnnotation)")
public void beforeMethod(JoinPoint joinPoint) {
System.out.println("Before executing method: " + joinPoint.getSignature().getName());
}
}
3. 创建一个Spring Boot应用
创建一个Spring Boot应用,并在主类中添加@EnableAspectJAutoProxy注解来启用AOP功能。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
4. 创建一个Service类
创建一个Service类,在其中的方法上加上自定义注解 @CustomAnnotation 。
import org.springframework.stereotype.Service;
@Service
public class MyService {
@CustomAnnotation
public void myMethod() {
System.out.println("Executing myMethod");
}
}
5. 在Controller中调用Service方法
创建一个Controller类,在其中调用Service类中被 @CustomAnnotation 注解标记的方法。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/execute")
public String executeMethod() {
myService.myMethod();
return "Method executed";
}
}
通过以上步骤,可以实现在Spring Boot应用中使用自定义注解和AOP来实现对方法的增强操作。当调用被 @CustomAnnotation 注解标记的方法时,AOP切面会在方法执行前输出日志信息。
原文链接: https://blog.csdn.net/2401_82884096/article/details/138335892