springAOP的代码案例
时间: 2024-01-22 19:03:33 浏览: 72
以下是一个简单的springAOP的代码案例:
1. 定义一个接口
```java
public interface UserService {
void addUser(String username, String password);
}
```
2. 实现接口
```java
public class UserServiceImpl implements UserService {
@Override
public void addUser(String username, String password) {
System.out.println("添加用户:" + username + ",密码:" + password);
}
}
```
3. 定义一个切面类
```java
@Aspect
@Component
public class LogAspect {
@Before("execution(* com.example.UserService.addUser(..))")
public void beforeAddUser(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
System.out.println("正在添加用户:" + args[0]);
}
}
```
4. 配置springAOP
```xml
<aop:aspectj-autoproxy/>
<bean id="userService" class="com.example.UserServiceImpl"/>
<bean id="logAspect" class="com.example.LogAspect"/>
```
5. 测试
```java
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
userService.addUser("Tom", "123456");
}
```
运行结果:
```
正在添加用户:Tom
添加用户:Tom,密码:123456
```
阅读全文