自定义注解步骤
1. 自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
String name();
// 可以在这里定义注解的属性
}
2. 自定义切面
@Aspect
@Component
public class MyCustomAnnotationAspect {
@Before("@within(myCustomAnnotation) || @annotation(myCustomAnnotation)")
public void beforeMethodWithCustomAnnotation(MyCustomAnnotation myCustomAnnotation) {
String name = myCustomAnnotation.name();
System.out.println("name = " + name);
// 在带有自定义注解的类或方法执行前执行的逻辑
System.out.println("Before method with custom annotation");
}
}
3. 在类或方法上添加自定义注解
@Controller
public class MyController {
@GetMapping("/annotation")
@MyCustomAnnotation(name = "zgd")
@ResponseBody
public String myMethod() {
System.out.println("执行了myMethod方法");
// 方法逻辑
return "example";
}
}
配置文件pom.xml的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
1072

被折叠的 条评论
为什么被折叠?



