1. 添加依赖项
确保在你的pom.xml
中添加了Spring AOP的依赖:
<dependencies>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.20</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
<!-- Spring Context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
</dependencies>
2. 创建业务服务类 UserService
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void addUser(String username) {
System.out.println("Adding user: " + username);
// 模拟业务逻辑
}
}
3. 创建切面类 LoggingAspect
package com.example.demo;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.demo.UserService.*(..))")
public void logBefore() {
System.out.println("LoggingAspect: Before method execution");
}
}
4. 配置Spring AOP
package com.example.demo;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("com.example.demo")
@EnableAspectJAutoProxy
public class AppConfig {
// 其他Bean配置(如果有)
}
5. 运行示例的主类 Application
package com.example.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Application {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
userService.addUser("John Doe");
}
}
代码解释
-
依赖项:
spring-aop
和aspectjweaver
是实现AOP所必需的。spring-context
用于管理Spring容器和应用上下文。
-
业务服务类
UserService
:- 这是一个简单的服务类,包含一个
addUser
方法,模拟添加用户的操作。
- 这是一个简单的服务类,包含一个
-
切面类
LoggingAspect
:- 使用
@Aspect
注解标识为切面。 @Before
注解定义了一个前置通知,在UserService
的任何方法执行前打印日志。- 切点表达式
execution(* com.example.demo.UserService.*(..))
表示匹配UserService
类中的所有方法。
- 使用
-
配置类
AppConfig
:- 使用
@Configuration
标识为配置类。 @ComponentScan
指定扫描的包。@EnableAspectJAutoProxy
启用AspectJ的自动代理功能,允许Spring处理AOP。
- 使用
-
主类
Application
:- 创建Spring应用上下文并加载配置。
- 获取
UserService
的Bean并调用其addUser
方法。由于AOP的配置,调用该方法时会先执行切面的前置通知,打印日志。
运行结果
当运行上述代码时,输出将是:
LoggingAspect: Before method execution Adding user: John Doe
总结
这个简单的示例展示了如何使用Spring AOP实现面向切面编程。通过定义切面和切点,可以在不修改业务逻辑代码的情况下,添加横切关注点(如日志记录)。这种模式有助于提高代码的模块化和可维护性,特别是在大型应用中非常有用。