AOP编程

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	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.xsd" default-autowire="byName">

<!--     配置代理关系               -->
<!-- 目标类      被代理人对象 -->
<bean id="target" class="dao.imp.UserDaoImp"></bean>
<!-- 切面  方面代码(通知代码)-->
<bean id="beforeAdvice" class="aop.BeforeAdvice"></bean>

<!-- 代理类   代理人对象-->
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">


<!-- 代理用到的接口     拦截者:指明方法代码的封装对象-->
<property name="proxyInterfaces">
<list>
<value>dao.UserDao</value>
</list>
</property>

<!-- 目标对象   指明被代理人-->
<property name="target" ref="target">
</property>


<!-- 切面 拦截者  :指明方面代码的封装对象 -->
<property name="interceptorNames">
<list>
<!-- <value>beforeAdvice</value> -->
<value>pointcutAndAdvice</value>
</list>
</property>
</bean>
<!-- 配置带切入点的bean 
进一步封装代码 ,提供过滤被代理方法的功能 。效果  :被代理接口中方法集合的子集被代理执行--> 
<bean id="pointcutAndAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
	<property name="advice" ref="beforeAdvice"></property>
	<property name="patterns">
		<list>
			<value>dao.UserDao.saveUser</value>
			<value>dao.UserDao.deleteUser</value>
		</list>
	</property>
</bean>
</beans>

applicationContext-aop.xml

 1  
 2 
 3 package aop;
 4 
 5 import java.lang.reflect.Method;
 6 import org.springframework.aop.MethodBeforeAdvice;
 7 
 8 public class BeforeAdvice implements MethodBeforeAdvice{
 9 
10     @Override
11     public void before(Method arg0, Object[] arg1, Object arg2)
12             throws Throwable {
13         //arg0 method; arg1参数列表 ; arg2目标对象
14         // TODO Auto-generated method stub
15         System.out.println("before");
16     }
17     
18     
19     
20     
21 }

 BeforeAdvice.java

 1 import org.springframework.context.ApplicationContext;
 2 import org.springframework.context.support.ClassPathXmlApplicationContext;
 3 
 4 import dao.UserDao;
 5 
 6 
 7 public class TestAop {
 8 
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11         ApplicationContext ctx=new ClassPathXmlApplicationContext("/applicationContext-aop.xml");
12         //获取文件
13         UserDao dao=(UserDao) ctx.getBean("proxy");
14         //得到代理
15         dao.saveUser();
16         dao.deleteUser();
17         dao.findUser();
18     }
19 
20 }

 测试页面   testaop.java

原文地址:https://www.cnblogs.com/tianhao/p/spring.html