Spring pointcut 获取注解
时间: 2024-05-06 10:17:38 浏览: 9
要在 Spring AOP 中获取注解,可以使用 `@annotation()` 切点函数。该函数可以匹配带有指定注解的方法。
以下是一个示例,演示如何使用 `@annotation()` 切点函数获取 `@MyAnnotation` 注解:
```java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
@Component
public class MyAspect {
@Before("@annotation(com.example.MyAnnotation)")
public void beforeMethodWithAnnotation() {
// 在带有 @MyAnnotation 注解的方法执行前执行
}
}
```
在这个示例中,`@Before` 注解指定了切面的执行时机,在带有 `@MyAnnotation` 注解的方法执行前执行切面的逻辑。
注意,`@MyAnnotation` 注解需要使用 `@Target(ElementType.METHOD)` 来标注它只能用于方法上,`@Retention(RetentionPolicy.RUNTIME)` 用于指定注解在运行时保留。
相关问题
spring的after注解
`@After` 是 Spring AOP 中的一个注解,用于指定某个方法在目标方法执行之后执行。
具体来说,当目标方法执行完成并返回时,`@After` 标注的方法就会被执行。这个注解通常用于一些清理工作,例如关闭资源等。
`@After` 注解可以用在 advice 方法上,也可以用在 pointcut 表达式上。在 advice 方法上使用 `@After` 注解,需要在方法签名中指定一个参数 `JoinPoint`,用于获取目标方法的一些信息,例如方法名、参数等。在 pointcut 表达式上使用 `@After` 注解,则表示该 pointcut 匹配的所有目标方法执行完成后都会执行该 advice 方法。
以下是一个使用 `@After` 注解的示例:
```java
@Aspect
@Component
public class MyAspect {
@After("execution(* com.example.service.*.*(..))")
public void after(JoinPoint joinPoint) {
System.out.println("执行完目标方法:" + joinPoint.getSignature().getName());
}
}
```
以上代码表示,在 `com.example.service` 包下所有方法执行完成后,会执行 `after` 方法,打印出目标方法的方法名。
spring有哪些注解
Spring框架中常用的注解包括:
1. @Autowired:自动装配,用于将一个bean注入到另一个bean中。
2. @Component:用于标识组件类,让Spring框架自动扫描并注册为bean。
3. @Controller:用于标识控制器类。
4. @Service:用于标识服务层类。
5. @Repository:用于标识数据访问层类。
6. @RequestMapping:用于映射请求路径到控制器方法。
7. @ResponseBody:用于将方法返回值序列化为JSON字符串等格式,并作为HTTP响应返回。
8. @PathVariable:用于获取请求路径中的变量。
9. @RequestParam:用于获取请求参数。
10. @Valid:用于校验请求参数。
11. @Transactional:声明方法需要事务支持。
12. @Aspect:声明切面类。
13. @Pointcut:用于声明切点。
14. @Before:用于声明前置通知。
15. @AfterReturning:用于声明后置通知。
16. @Around:用于声明环绕通知。
等等。