使用注解AOP
时间: 2023-10-03 12:04:39 浏览: 50
注解AOP是一种基于注解的AspectJ AOP实现方式。在使用注解AOP时,我们需要定义切面类,并在切面类中定义各个增强方法。同时,我们需要在需要进行增强的目标方法上添加相应注解,以表明该目标方法需要被哪些增强方法所增强。
具体实现步骤如下:
1. 定义切面类,使用@Aspect注解标注该类,并在该类中定义各个增强方法。
2. 在增强方法上使用@Before、@After、@Around等注解标注,以表明该增强方法是在目标方法之前、之后或者环绕目标方法执行。
3. 在需要进行增强的目标方法上添加相应注解,例如@Before、@After、@Around等注解,以表明该目标方法需要被哪些增强方法所增强。
4. 在Spring配置文件中通过<aop:aspectj-autoproxy/>标签开启注解AOP的支持。
下面是一个简单的注解AOP示例代码:
```java
@Aspect
@Component
public class MyAspect {
@Pointcut("execution(* com.example.service.UserService.addUser(..))")
public void addUser() {}
@Before("addUser()")
public void beforeAddUser() {
System.out.println("开始添加用户...");
}
@After("addUser()")
public void afterAddUser() {
System.out.println("添加用户成功。");
}
}
@Service
public class UserService {
public void addUser() {
System.out.println("正在添加用户...");
}
}
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.example")
public class AppConfig {
}
```
在上面的示例代码中,我们定义了一个切面类MyAspect,并在该类中定义了两个增强方法beforeAddUser和afterAddUser。同时,我们在UserService的addUser方法上添加了@Before和@After注解,以表明该方法需要在目标方法之前和之后被增强。最后,在Spring配置文件中通过@EnableAspectJAutoProxy注解和@ComponentScan注解启用注解AOP的支持,并扫描相关的组件。