Spring AOP 实战案例:使用切面打印日志
假设我们有一个 UserService 接口和实现类 UserServiceImpl,其中有一个 addUser 方法用于添加用户信息。我们希望在该方法执行前后分别打印日志。
- 定义切面类
首先,我们需要定义一个切面类来实现日志的打印。该类需要实现 Spring 的 AOP 接口——org.aspectj.lang.annotation.Aspect,同时需要使用注解来标识切面的类型和具体的切点。
@Aspect
@Component
public class LogAspect {
@Pointcut("execution(* com.example.service.UserService.addUser(..))")
public void addUserPointcut() {}
@Before("addUserPointcut()")
public void beforeAddUser() {
System.out.println('开始添加用户信息...');
}
@After("addUserPointcut()")
public void afterAddUser() {
System.out.println('用户信息添加完成。');
}
}
上述代码中,我们定义了一个切点 addUserPointcut,它表示所有执行 UserService 的 addUser 方法的连接点。同时,我们在切面类中定义了两个通知方法——beforeAddUser 和 afterAddUser,它们分别表示在 addUser 方法执行前和执行后需要做的操作。
- 配置 AOP
接下来,我们需要在 Spring 配置文件中配置 AOP。我们需要声明切面类和切点,并使用 aop:aspectj-autoproxy 标签来开启自动代理。
<bean id="logAspect" class="com.example.aop.LogAspect"/>
<aop:config>
<aop:aspect ref="logAspect">
<aop:pointcut id="addUserPointcut" expression="execution(* com.example.service.UserService.addUser(..))"/>
<aop:before pointcut-ref="addUserPointcut" method="beforeAddUser"/>
<aop:after pointcut-ref="addUserPointcut" method="afterAddUser"/>
</aop:aspect>
</aop:config>
<aop:aspectj-autoproxy/>
上述代码中,我们首先定义了切面类 logAspect,并将其声明为 Spring 的 bean。接下来,我们使用 aop:config 标签进行 AOP 配置。在此标签中,我们声明了一个切点 addUserPointcut,并将其绑定到 logAspect 切面类上。然后,我们使用 aop:before 和 aop:after 标签来分别指定在 addUserPointcut 连接点执行前和执行后需要调用的方法。
最后,我们使用 aop:aspectj-autoproxy 标签来开启自动代理,以便让 Spring 自动创建代理对象并应用切面。
- 测试
现在,我们可以编写一个测试类来测试 AOP 的效果。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config.xml")
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testAddUser() {
User user = new User();
user.setId(1);
user.setName("张三");
userService.addUser(user);
}
}
上述代码中,我们使用 Spring 的测试框架来运行测试,并使用 @ContextConfiguration 注解来指定 Spring 配置文件的路径。在测试方法中,我们调用 UserService 的 addUser 方法来添加一个用户,这时切面类中的通知方法会被自动调用,打印日志信息。
完整的示例代码可以参考以下链接:https://github.com/linjiajian999/Spring-AOP-Demo
原文地址: https://www.cveoy.top/t/topic/m64S 著作权归作者所有。请勿转载和采集!