首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

AOP动态署理spring框架的实现

2012-10-16 
AOP动态代理spring框架的实现spring里面封装好了这个,只需要给配置上就可以了,框架总是这样,除了配置还有

AOP动态代理spring框架的实现
spring里面封装好了这个,只需要给配置上就可以了,框架总是这样,除了配置还有什么,如果你只想会用的话.

package com.itcast.service;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;@Aspectpublic class MyInterceptor {//第一个*代表返回值的类型,下面是..对子包下面的类进行拦截,*代表类 *代笔方法(..)代笔方法的参数@Pointcut("execution(* com.itcast.service.UserService.*(..))")private void anyMethod(){}//想在执行方法前输出一句话,前置通知@Before("anyMethod() && args(username)")public void doAcessCheck(String username){System.out.println("检查权限......-->>前置通知"+username);}@AfterReturning(pointcut="anyMethod()" ,returning="returnValue")public void doAfterLogin(String returnValue){System.out.println("日志记录....."+returnValue);}@After("anyMethod()")public void doAter(){System.out.println("最终通知-------->>>>");}@AfterThrowing(pointcut="anyMethod()",throwing="ex")public void doException(Exception ex){System.out.println("异常处理---->>例外通知"+ex);}@Around("anyMethod()")public void doBasicProfiling(ProceedingJoinPoint pjp)throws Throwable{//if(){权限验证System.out.println("进入方法");pjp.proceed();System.out.println("退出方法");}}


最容易忘记要在beans.xml里面声明,不然spring怎么知道你要咋搞

<?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-2.5.xsd           http://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"><aop:aspectj-autoproxy/><bean id="userDao" ><property name="userdao" ref="userDao"></property></bean><bean id="aopinterceptor" name="code">package com.itcast.service.imp;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.context.support.AbstractApplicationContext;import com.itcast.service.UserService;public class UserServiceTest {@Testpublic void testSave(){AbstractApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");UserService userser=(UserService)ac.getBean("userService");userser.Loin("张三");ac.close();}}


基本OK,底层还是前面那个,如果有接口就用JDK,没有就用Cglib

热点排行