AOP编程

时间:2024-01-15 23:32:56
<?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


 package aop;

 import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice; public class BeforeAdvice implements MethodBeforeAdvice{ @Override
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
//arg0 method; arg1参数列表 ; arg2目标对象
// TODO Auto-generated method stub
System.out.println("before");
} }

BeforeAdvice.java

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import dao.UserDao; public class TestAop { public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx=new ClassPathXmlApplicationContext("/applicationContext-aop.xml");
//获取文件
UserDao dao=(UserDao) ctx.getBean("proxy");
//得到代理
dao.saveUser();
dao.deleteUser();
dao.findUser();
} }

测试页面   testaop.java