面试题答案
一键面试- 定义自定义注解:
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 MyAnnotation { // 可以根据需要添加属性 String value() default ""; }
- 定义切面类:
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @Aspect public class MyAspect { @Around("@annotation(myAnnotation)") public Object aroundMethod(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) throws Throwable { System.out.println("在方法执行前,注解的值:" + myAnnotation.value()); Object result = joinPoint.proceed(); System.out.println("在方法执行后"); return result; } }
- 在目标类方法上使用注解:
public class TargetClass { @MyAnnotation("示例注解值") public void targetMethod() { System.out.println("目标方法执行"); } }
- 配置AspectJ:
- 如果使用Spring Boot项目,在
pom.xml
中添加AspectJ依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter - aspectjweaver</artifactId> </dependency>
- 在Spring配置文件(如
application.properties
)中开启AspectJ自动代理:
spring.aop.auto=true
- 如果使用Spring Boot项目,在
通过以上步骤,在Java项目结合AspectJ框架,通过自定义Java注解定义了切入点,并实现了切面逻辑。