springAOP代码示例
时间: 2023-10-28 17:12:11 浏览: 38
以下是一个简单的Spring AOP代码示例,用于记录方法执行时间:
1. 定义一个切面类,实现Advice接口
```java
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class TimeAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object obj = invocation.proceed();
long endTime = System.currentTimeMillis();
System.out.println("方法" + invocation.getMethod().getName() + "执行时间为:" + (endTime - startTime) + "ms");
return obj;
}
}
```
2. 在Spring配置文件中定义切面和切点
```xml
<bean id="timeAspect" class="com.example.TimeAspect"/>
<aop:config>
<aop:aspect ref="timeAspect">
<aop:pointcut id="serviceMethods" expression="execution(* com.example.service.*.*(..))"/>
<aop:around pointcut-ref="serviceMethods" method="invoke"/>
</aop:aspect>
</aop:config>
```
3. 在业务类中使用切面
```java
import com.example.service.UserService;
public class UserController {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void addUser(String username, String password) {
userService.addUser(username, password);
}
public void deleteUser(String username) {
userService.deleteUser(username);
}
public void updateUser(String username, String password) {
userService.updateUser(username, password);
}
}
```
代码说明:
- 在切面类中,实现了MethodInterceptor接口,重写了invoke方法,在方法执行前记录开始时间,在方法执行后记录结束时间,并打印执行时间。
- 在Spring配置文件中,定义了一个切面bean和一个切点,切面bean引用了切面类,切点定义了需要被切入的方法,使用了表达式execution(* com.example.service.*.*(..)),表示拦截com.example.service包下的所有方法。
- 在业务类中,注入了一个UserService的实例,业务方法调用了UserService的方法,实现了切面的切入。