读书人

spring的第一个AOP范例

发布时间: 2012-12-20 09:53:21 作者: rapoo

spring的第一个AOP实例
面向切面编程,要理解很多概念,如切面,连接点,通知,切入点。。。
此时新建的项目不仅要添加spring的核心包(即core),还有添加AOP功能的jar包
然后创建bean类
先创建接口

package com.sun.springaop.test;public interface IBean {public void theMethod();}

然后创建实现类
package com.sun.springaop.test;public class BeanImpl implements IBean {@Overridepublic void theMethod() {System.out.println(this.getClass().getName()+"."+new Exception().getStackTrace()[0].getMethodName()+"()"+" 正在被执行");}}

创建前置通知类,即在操作前执行的功能
package com.sun.springaop.test;import java.lang.reflect.Method;import org.springframework.aop.MethodBeforeAdvice;public class TestBeforeAdvice implements MethodBeforeAdvice {//参数method表示具体连接点,args表示目标对象方法的参数,target返回该方法所属的目标对象@Overridepublic void before(Method m, Object[] args, Object target)throws Throwable {System.out.println("执行前置通知");}}

在配置文件中,进行拦截器和bean的配置
完整的配置文件如下:
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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-2.0.xsd"><!-- 定义代理 --><bean id="bean"lazy-init="default" autowire="default"dependency-check="default"><property name="proxyInterfaces"><value>com.sun.springaop.test.IBean</value></property><property name="target"><ref local="beanTarget" /></property><property name="interceptorNames"><list><value>theAdvisor</value></list></property></bean><!-- 注入对象 --><bean id="beanTarget" lazy-init="default" autowire="default"dependency-check="default"></bean><!-- 使用正则表达式方式定义切入点 --><bean id="theAdvisor"lazy-init="default" autowire="default"dependency-check="default"><property name="advice"><ref local="theBeforeAdvice" /></property><property name="pattern"><value>com\.sun\.springaop\.test\.IBean\.theMethod</value></property></bean><!-- 定义前置通知 --><bean id="theBeforeAdvice"abstract="false"lazy-init="default" autowire="default" dependency-check="default"></bean></beans>

测试类:
package com.sun.springaop.test;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;public class Client {public static void main(String[] args) {BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));IBean x = (IBean) factory.getBean("bean");x.theMethod();}}

执行结果:
执行前置通知
com.sun.springaop.test.BeanImpl.theMethod() 正在被执行

读书人网 >编程

热点推荐