spring中使用AspectJ的案例
时间: 2024-05-06 13:20:16 浏览: 9
以下是一个简单的Spring中使用AspectJ的案例:
1. 定义切面类
```java
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before " + joinPoint.getSignature().getName() + " method is called");
}
@After("execution(* com.example.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("After " + joinPoint.getSignature().getName() + " method is called");
}
}
```
上面的代码定义了一个切面类`LoggingAspect`,其中包含了两个通知方法`logBefore`和`logAfter`,分别在目标方法执行前和执行后打印日志。
2. 配置Spring AOP
```xml
<aop:aspectj-autoproxy />
<bean id="loggingAspect" class="com.example.aspect.LoggingAspect" />
```
在Spring配置文件中加入以上两行配置,启用AspectJ自动代理和定义切面类。
3. 使用切面
```java
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUserById(int id) {
System.out.println("getUserById(" + id + ")");
return new User(id, "John");
}
@Override
public void saveUser(User user) {
System.out.println("saveUser(" + user + ")");
}
}
```
在目标类`UserServiceImpl`的方法上不需要添加任何注解或配置,AspectJ会自动将切面织入到这些方法中。
4. 测试
```java
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean(UserService.class);
userService.getUserById(1);
userService.saveUser(new User(2, "Alice"));
}
}
```
运行上面的代码,可以看到控制台输出:
```
Before getUserById method is called
getUserById(1)
After getUserById method is called
Before saveUser method is called
saveUser(User [id=2, name=Alice])
After saveUser method is called
```
这表明切面已经成功织入到了目标方法中。