AOP

来源:互联网 发布:投资保姆软件下载 编辑:程序博客网 时间:2024/06/07 02:09

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

主要功能

日志记录,性能统计,安全控制,事务处理,异常处理等等



主要意图

将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。
实例之日志记录
定义一个简单接口实现类
public class HelloWorldServiceImpl implements HelloWorldService {@Overridepublic void say(String msg) {System.out.println("say to world: "+msg);//System.out.println(1/0);}}
测试类
public class TestAop {private ApplicationContext ac;@Beforepublic void setUp() throws Exception {ac = new ClassPathXmlApplicationContext("beans.xml");}@Testpublic void test(){HelloWorldService hw = (HelloWorldService) ac.getBean("helloWorldService");hw.say("hello");}}

日志输出类
public class HelloServiceAspect {//前置通知public void doBefore(JoinPoint jp){System.out.println("类名:"+ jp.getTarget().getClass().getName());System.out.println("方法名:"+ jp.getSignature().getName());System.out.println("内容: "+ jp.getArgs()[0]);System.out.println("开始说话");}//后置通知public void doAfter(JoinPoint jp){System.out.println("说话完成");}//环绕通知public Object doAround(ProceedingJoinPoint pjp) throws Throwable{System.out.println("环绕通知前");Object proceed = pjp.proceed();System.out.println("环绕通知后");return proceed;}//异常通知public void doAfterThrowing(JoinPoint jp, Throwable ex){System.out.println("异常通知");System.out.println("异常信息: "+ ex.getMessage());}}

配置文件
<?xml version="1.0" encoding="UTF-8"?><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.xsdhttp://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop.xsd"><bean id="helloServiceAspect" class="spring.advice.HelloServiceAspect"></bean><bean id="helloWorldService" class="spring.service.impl.HelloWorldServiceImpl"></bean><aop:config><aop:aspect id="helloServiceAspect" ref="helloServiceAspect"><aop:pointcut expression="execution(* spring.service.*.*(..))" id="businessService"/><aop:before method="doBefore" pointcut-ref="businessService"/><aop:after method="doAfter" pointcut-ref="businessService"/><aop:around method="doAround" pointcut-ref="businessService"/><aop:after-throwing method="doAfterThrowing" pointcut-ref="businessService" throwing="ex"/></aop:aspect></aop:config></beans>

正则表达式含义:第一个*表示返回值任意,第二个表示任意类,第三个表示任意方法,(..)表示传参任意
以上是四种常用得配置,前置通知、后置通知、环绕通知、异常通知




0 0
原创粉丝点击