使用注解配置Spring AOP

本文介绍如何利用Spring框架整合AspectJ实现面向切面编程(AOP),通过具体实例展示了如何配置切面、切入点和增强等功能,并实现了事务管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    Spring框架提供通过注解方式配置的生命是SOP功能,是基于AspectJ实现的。


   AspectJ提供整套AOP理论的完整实现,很多其他的AOP实现(包括其他语言)都借鉴了AspectJ的一些思想,AspectJ的很多实现方式已经成为AOP领域的事实标准。即使不使用Spring框架,也可直接使用AspectJ进行AOP编程,AspectJ允许使用注解来定义切面,切入点和增强,而Spring框架可以识别并根据这些注解生成AOP代理。


   准备Aspect注解:

为了使用AspectJ注解方式,需要配置Spring AOP,首先要在Spring配置文件中声明<aop:aspectj-autoproxy>元素。同<aop:config>元素类似,<aop:aspectj-autoproxy>元素也具有proxy-target-class和expose-proxy属性。


   配置切面说明:

   实施增强的TransactionManager类需要配置为切面,AspectJ提供了下列注解用于配置切面,这些注解都位于org.aspectj.lang.annotation包下面。

●@Aspect:配置一个类为切面类

●@Before:配置一个方法为前置增强

●@After:配置一个方法为后置增强

●@AfterReturning:配置一个方法为返回后增强

●@AfterThrowing:配置一个方法为抛出异常后增强

●@Around:配置一个方法为环绕增强

●@DeclareParents:配置一个类为引介增强


下面通过例子进行演示:

(1)首先编写业务类,业务类GoodService,没有实现任何接口,代码如下:

<span style="font-size:18px;"><strong>package com.loster.li.spring_aop;

public class GoodsService {
	private static int ORDER_NO = 1000;  //用于生成订单编号
	
	public int buyGoods(String user,String productName){
		ORDER_NO++;
		System.out.println("【数据库插入订单】购买者"+user+",商品:"+productName
							+",订单编号:"+ORDER_NO);
		return ORDER_NO;
	}
	public void returnGoods(int orderNo){
		System.out.println("【数据库修改订单状态】订单编号:"+orderNo);
	}
}</strong></span>
(2)编写切面类,通过注解使事务管理类TransactionManager用于对业务类进行增强:

<span style="font-size:18px;"><strong>package com.loster.li.spring_aop;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class TransactionManager_AspectJ {
	
	@Before("execution(* com.loster.li.spring_aop.*Service.*(..))")
	public void beginTransaction(){
		System.out.println("【事务管理器】开始事务");
	}
	@AfterReturning("execution(* com.loster.li.spring_aop.*Service.*(..))")
	public void commit(){
		System.out.println("【事务管理器】提交事务");
	}
	@AfterThrowing("execution(* com.loster.li.spring_aop.*Service.*(..))")
	public void rollback(){
		System.out.println("【事务管理器】回滚事务");
	}
}</strong></span>
(3)在Spring配置文件中配置AOP,命名为applicationContext_AspectJ.xml,其代码如下:

<span style="font-size:18px;"><strong><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	<!-- 业务类  -->
	<bean id = "service" class = "com.loster.li.spring_aop.GoodsService"></bean>
	
	<!-- 切面类 -->
	<bean id = "transactionManager" class = "com.loster.li.spring_aop.TransactionManager_AspectJ"></bean>
	
	<!-- 开启AspectJ注释 -->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans></strong></span>
(4)编写测试类test2.java:

<span style="font-size:18px;"><strong>package com.loster.li.spring_aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test2 {
	public static void main(String[] args){
		ApplicationContext context = new ClassPathXmlApplicationContext(
						"/com/loster/li/spring_aop/applicationContext_AspectJ.xml");
		GoodsService service = (GoodsService)context.getBean("service");
		service.buyGoods("June", "Python");    //购买商品
		service.returnGoods(3100);             //退货
	}
}</strong></span>

(5)运行test2.java,结果如下:


Spring使用注解配置 AOP 的步骤主要包括以下几个方面: ### 1. 引入必要的依赖 首先需要确保项目的构建文件中有相应的 AOP 支持库。如果是 Maven 构建工具,可以在 `pom.xml` 文件中添加如下依赖: ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>{Spring版本号}</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>{AspectJ版本号}</version> </dependency> ``` ### 2. 启用 AOP 注解支持 要在应用上下文中启用基于注解AOP 功能,需在主配置类上加上 `@EnableAspectJAutoProxy` 注解: ```java @Configuration @EnableAspectJAutoProxy public class AppConfig { } ``` 这行代码告诉 Spring 容器开启对 @Aspect 标记切面的支持。 ### 3. 创建切面(Aop) 接下来创建一个普通的 Java 类,在该类顶部声明它是一个切面(`@Aspect`) 并注册为 Bean (`@Component`): ```java @Component @Aspect public class LoggingAspect { // 切点表达式指定拦截规则 @Before("execution(* com.example.service.*.*(..))") public void beforeAdvice(){ System.out.println("Method is going to start"); } @AfterReturning("execution(* com.example.service.*.*(..))") public void afterReturningAdvice() { System.out.println("Method has completed successfully."); } @AfterThrowing(pointcut="execution(* com.example.service.*.*(..))", throwing="ex") public void afterThrownException(Exception ex){ System.err.println("Error occurred in method:" + ex.getMessage()); } @Around("execution(* com.example.service.*.*(..))") public Object aroundAdvice(ProceedingJoinPoint point) throws Throwable{ long beginTime=System.currentTimeMillis(); try { return point.proceed(); // 执行原定方法内容 }finally{ System.out.println("The execution time of the method was "+ (System.currentTimeMillis()-beginTime)); } } } ``` 以上示例展示了如何利用四种基本的通知类型来实现前置、后置及环绕通知等功能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值