java AOP如何使用
时间: 2023-12-14 11:04:12 浏览: 23
Java AOP(面向切面编程)是一种编程范式,它允许开发人员在不改变源代码的情况下,通过拦截方法调用等方式,进行统一的处理和控制。下面是使用Java AOP的一般步骤:
1. 添加AOP框架:需要引入AOP框架,如AspectJ、Spring AOP等
2. 定义切面:切面是一组通知和切点的组合。通知定义了在切点执行前、执行后、抛出异常等时刻所要执行的逻辑,而切点则定义了在哪些地方应用这些通知。
3. 配置切面:需要将切面配置到应用中,以便在运行时生效。
4. 编写业务逻辑:编写需要被拦截的业务逻辑代码。
5. 运行应用:启动应用,观察AOP是否生效。
下面是一个使用Spring AOP的示例代码:
定义切面
```java
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.demo.service.UserService.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before method execution: " + joinPoint.getSignature().getName());
}
@After("execution(* com.example.demo.service.UserService.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("After method execution: " + joinPoint.getSignature().getName());
}
}
```
配置切面
```java
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
@Bean
public LoggingAspect loggingAspect() {
return new LoggingAspect();
}
}
```
编写业务逻辑
```java
@Service
public class UserService {
public void addUser(String username, String password) {
System.out.println("Adding user: " + username);
}
public void deleteUser(String username) {
System.out.println("Deleting user: " + username);
}
}
```
运行应用
```java
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
userService.addUser("John", "123456");
userService.deleteUser("John");
}
```
输出结果为:
```
Before method execution: addUser
Adding user: John
After method execution: addUser
Before method execution: deleteUser
Deleting user: John
After method execution: deleteUser
```