Spring中AOP的使用(XML)

本文记录Java学习过程中遇到的Spring中AOP的使用~

1.导包

spring传统的AOP的开发包

  • spring-aop-xxx.jar
  • com.springsource.org.aopalliance-xxx.jar

AspectJ的开发包

  • com.springsource.org.aspectj.weaver-xxx.jar
  • spring-aspects-xxx.jar

2.XML配置文件引入AOP约束

<beans 
	xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>

3.编写目标类

// 接口
public interface OrderDao {
	public void save();
	public void update();
	public void delete();
	public void find();
}

// 实现类
public class OrderDaoImpl implements OrderDao {

	@Override
	public void save() {
		System.out.println("save");
	}

	@Override
	public void update() {
		System.out.println("update");
	}

	@Override
	public void delete() {
		System.out.println("delete");
	}

	@Override
	public void find() {
		System.out.println("find");
	}
}

4.目标类的配置

<!-- 目标类的配置 -->
<bean id="orderDao" class="ren.oliver.spring.OrderDaoImpl" />

5.编写切面类

public class MyAspectXml {
	// 前置增强
	public void before() {
		System.out.println("before");
	}
}

6.配置完成增强

<!-- 配置切面类 -->
<bean id="myAspectXml" class="ren.oliver.spring.MyAspectXml" />

<!-- 进行AOP配置 -->
<aop:config>
	<!-- 配置切入点表达式:哪些类的哪些方法需要进行增强 -->
	<aop:pointcut expression="execution(*ren.oliver.spring.OrderDao.*(..))" id="pointcut" />
	<!-- 配置切面 -->
	<aop:aspect ref="myAspectXml">
		<aop:before method="before" pointcut-ref="pointcut" />
		<aop:after-returning method="afterReturning" pointcut-ref="pointcut" />
		<aop:around method="around" pointcut-ref="pointcut" />
		<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" />
		<aop:after method="after" pointcut-ref="pointcut" />
	</aop:aspect>
</aop:config>

标签: none