`

AOP

阅读更多

静态代理
通过接口实现

动态代理

1 编写java代理类

public class SecurityHandler implements InvocationHandler {
    
private Object targetObject;
    
//创建代理类
    public Object newProxy(Object targetObject){
        
this.targetObject=targetObject;
        
return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
                                      targetObject.getClass().getInterfaces(),
                                      
this);
    }

    
//
    public Object invoke(Object proxy, Method method, Object[] args)
            
throws Throwable {
        checkSecurity();
        Object result
=null;
        
try {
            result
=method.invoke(this.targetObject, args);
        }
 catch (RuntimeException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        
return result;
    }

    
    
private void checkSecurity(){
        System.out.println(
"------------checkSecurity-------------");
    }

}
2 调用
SecurityHandler handler=new SecurityHandler();
    UserManager userManager
=(UserManager)handler.newProxy(new UserManagerImpl());
    userManager.addUser(
"张三""123456");
----------------------------------------------------------------------------------------------------------------------

spring对AOP的支持(采用Annotation的方式)注解方式

AOP:
   * Cross cutting concern 横切性关注点
   * Aspect 切面,是对横切性关注点的模块化
   * Advice 横切性关注点的实现,切面的实现
   * Piontcut Advice应用范围的表达式
   * Joinpoint 执行的点,spring中是方法
   * Weave Advice

1  spring的依赖库
  * SPRING_HOME/dist/spring.jar
  * SPRING_HOME/lib/jakarta-commons/commons-logging.jar
  * SPRING_HOME/lib/log4j/log4j-1.2.14.jar
  * SPRING_HOME/lib/aspectj/*.jar(aspectjrt.jar/aspectjweaver.jar)
---applicationContext.xml

   <?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"***************
       xmlns:context
="http://www.springframework.org/schema/context"
       xsi:schemaLocation
="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop       ****************
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
>****
    
<context:annotation-config />//开启配置项
    
<aop:aspectj-autoproxy />

    
<bean id="personDao" class="org.spring.dao.impl.PersonDaoImpl"/>
    
</beans>
2  采用Aspect定义切面,在Aspect定义Pointcut和Advice
    示例:
@Aspect //切面
        public class SecurityHandler  {
            
/** *//**
             * Pointcut,Pointcut的名称就是allAddMethod,此方法不能有返回值和参数,该方法只一个标识
             * Pointcut的内容是一个表达式,描述那些对象的那些方法(订阅Joinpoint)
             * 定义
             
*/

            @Pointcut(
"execution(* add*(..)) || execution(* del*(..))")
            
//@Pointcut("execution(* org.my.biz..*.*(..))")
            private void allAddMethod(){};
            
/** *//**
             * 定义Advice,标识在那个切入点何处织入些方法
             
*/

            @Before(
"allAddMethod() && args(name)")//前置通知
            [@AfterReturning("allAddMethod()")后置通知,可以同时存在]
            [@After(
"allAddMethod()")最终通知]
            [AfterThrowing(
"allAddMethod()")例外通知,抛异常时]
            
private void checkSecurity(String name){
                System.out.println(
"------------checkSecurity-------------");
                System.out.println(name);
            }

            @Around(
"allAddMethod()")//环绕通知
            public Object doBasicProfiling(ProceedingJoinPiont pjp) throws Throwable{
              
if(){//判断是否有权限
                System.out.println("进入方法");
                    Object result
=pjp.proceed();//如果不调用这个方法,后面的业务bean及切面将不会执行
                  }

                
return result;
            }

        }
3  启用Aspect对Annotation的支持并且将Aspect类和目标对象配置到Ioc容器中
<aop:aspectj-autoproxy />
   
<bean id="securityHandler" class="com.my.spring.SecurityHandler"/>
     
<bean id="userManager" class="com.my.spring.UserManagerImpl"/>
4 调用
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
    UserManager userManager
=(UserManager)factory.getBean("userManager");
  userManager.addUser(
"张三""123456");
注意:在这各方法定义中,切入点的方法是不被执行的,它存在的目的仅仅是为了重用切入点
即Advice中通过方法名引用这个切入点
手动添加schema文件,方法如下:
windows->preferences->myeclipse->files and editors->xml->xmlcatalog
--------------------------------------------------------------------------------------------------

spring对AOP的支持(采用配置文件的方式)

Aspect默认情况下不用实现接口,但对于目标对象(UserManagerImpl.java),在默认情况下必须实现接口,
如查没有实现接口必须引入CGLIB库
我们可以通过Advice中添加一个JoinPoint参数,这个值会由spring自动传入,从JoinPoint中可以取得能数值、方法名等等

1  spring的依赖库
  * SPRING_HOME/dist/spring.jar
  * SPRING_HOME/lib/jakarta-commons/commons-logging.jar
  * SPRING_HOME/lib/log4j/log4j-1.2.14.jar
  * SPRING_HOME/lib/aspectj/*.jar(aspectjrt.jar/aspectjweaver.jar)
2  定义切面类

public class SecurityHandler  {
            
private void checkSecurity(JoinPoint joinPoint){
              Object[] args
=joinPoint.getArgs();//得到参数集合
              for(int i=0;i<args.length;i++){
                      System.out.println(args[i]);
              }

              System.out.println(joinPoint.getSignature().getName());
//得到方法名
                System.out.println("------------checkSecurity-------------");
            }

        }
3  在配置文件中配置
   * xml方式
<bean id="securityHandler" class="com.my.spring.SecurityHandler"/>
        
<bean id="userManager" class="com.my.spring.UserManagerImpl"/>
        
<aop:config>
            
<aop:aspect id="security" ref="securityHandler">
                
<aop:pointcut id="allAddMethod" expression="execution(* add*(..))"/>
                
<aop:before method="checkSecurity" pointcut-ref="allAddMethod"/>
<!--
                <aop:after method="checkSecurity" pointcut-ref="allAddMethod"/>
                <aop:after-returning method="checkSecurity" pointcut-ref="allAddMethod"/>
                <aop:after-throwing method="checkSecurity" pointcut-ref="allAddMethod"/>
                <aop:around method="checkSecurity" pointcut-ref="allAddMethod"/>
-->
            
</aop:aspect>
        
</aop:config>
4  调用
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserManager userManager
=(UserManager)factory.getBean("userManager");
        userManager.addUser(
"张三""123456");
---------------------------------------------------------------------------------------------------
JDK动态代理和CGLIB
手动编写代码:
public class CGlibProxy implements MethodInterceptor{
    
private Object targetObject;//代理目标对象
    public Object createProxyIntance(Object targetObject){
        
this.targetObject=targetObject;
        Enhancer enhancer
=new Enhancer();//该类用于生成代理对象
        
//非final,继承目标类,并对非final方法进行复盖
        enhancer.setSuperclass(this.targetObject.getClass());//设置父类
        enhancer.setCallback(this);//设置回调用对象为本身
        return enhancer.create();
    }

    @Override
    
public Object intercept(Object proxy, Method mothod, Object[] args,
            MethodProxy methodProxy) 
throws Throwable {
        PersonServiceBean bean
=(PersonServiceBean)this.targetObject;
        Object result
=null;
        
if(bean.getUser()!=null){//判断是否为空
            result=methodProxy.invoke(targetObject, args);
        }

        
return null;
    }

}

//test方法
CGlibProxy cglibProxy=new CGlibProxy();
        PersonServiceBean personServiceBean
=(PersonServiceBean)cglibProxy.createProxyIntance(new PersonServiceBean());
        personServiceBean.save(
"dddddd");

spring对AOP的支持
1 如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP
2 如果目标对象实现了接口,可以强制使用CGLIB实现AOP
3 如查目标对象没有实现接口,必须采用CGLIB库,spring会自动在JDK动态代理和CGLIB之间转换

如何强制使用CGLIB实现AOP?
   * 添加CGLIB库,在SPRING_HOME/cglib/*.jar
   * 在该spring配置文件中加入<aop:aspectj-autoproxy proxy-target-class="true"/>
  
JDK动态代理和CGLIB字节码生成的区别:
  * JDK动态代理只能对实现了接口的类生成代理,而不能针对类
  * CGLIB是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法
 因为是继承,所以该类或方法最好不要声明成final

-------------------------------------------------------------------------------------------------------
spring1.2 AOP实现方法
1 advice类
public class LogAdvice implements MethodBeforeAdvice {
    
public void before(Method m, Object[] arg1, Object arg2)
            
throws Throwable {    
        System.out.println(
new Date()+"时间,调用了,"+m.getName()+"方法,参数为"+Arrays.toString(arg1));
    }

}


public class JiaAdvice implements AfterReturningAdvice {
    
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
            Object arg3) 
throws Throwable {
        System.out.println(
"给qian了");        
    }

}
2 biz类
public class HelloBizImpl implements HelloBiz {
    
public void say(String username) {
        System.out.println(
"欢迎你"+username);
    }

    
public void sayHello(String word) {    
        System.out.println(word);
    }

}
</spa
分享到:
评论

相关推荐

    spring-aop.jar各个版本

    spring-aop-1.1.1.jar spring-aop-1.2.6.jar spring-aop-1.2.9.jar spring-aop-2.0.2.jar spring-aop-2.0.6.jar spring-aop-2.0.7.jar spring-aop-2.0.8.jar spring-aop-2.0.jar spring-aop-2.5.1.jar spring-aop-...

    开发工具 spring-aop-4.3.6.RELEASE

    开发工具 spring-aop-4.3.6.RELEASE开发工具 spring-aop-4.3.6.RELEASE开发工具 spring-aop-4.3.6.RELEASE开发工具 spring-aop-4.3.6.RELEASE开发工具 spring-aop-4.3.6.RELEASE开发工具 spring-aop-4.3.6.RELEASE...

    spring-aop-5.2.0.RELEASE-API文档-中文版.zip

    赠送jar包:spring-aop-5.2.0.RELEASE.jar; 赠送原API文档:spring-aop-5.2.0.RELEASE-javadoc.jar; 赠送源代码:spring-aop-5.2.0.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-aop-5.2.0.RELEASE.pom;...

    spring aop 自定义注解保存操作日志到mysql数据库 源码

    3、对spring aop认识模糊的,不清楚如何实现Java 自定义注解的 4、想看spring aop 注解实现记录系统日志并入库等 二、能学到什么 1、收获可用源码 2、能够清楚的知道如何用spring aop实现自定义注解以及注解的逻辑...

    Java利用spring aop进行监测方法执行耗时

    使用 Spring AOP 进行方法耗时监测的好处有以下几点: 1. 代码实现简单,易于维护:使用 Spring AOP 可以将耗时监测的逻辑与业务逻辑进行解耦,避免业务逻辑代码的冗余和代码维护难度的提高。 2. 安全性高:使用 ...

    开发工具 aopalliance-1.0

    开发工具 aopalliance-1.0开发工具 aopalliance-1.0开发工具 aopalliance-1.0开发工具 aopalliance-1.0开发工具 aopalliance-1.0开发工具 aopalliance-1.0开发工具 aopalliance-1.0开发工具 aopalliance-1.0开发工具...

    Asp.net Core 3.1基于AspectCore实现AOP实现事务、缓存拦截器功能

    AOP的概念也很好理解,跟中间件差不多,说白了,就是我可以任意地在方法的前面或后面添加代码,这很适合用于缓存、日志等处理。 在net core2.2时,我当时就尝试过用autofac实现aop,但这次我不想用autofac,我用了一...

    spring aop spring aop

    spring aop spring aop spring aop spring aop spring aop spring aop spring aop spring aop spring aop

    springBoot+aop+自定义注解+本地线程实现统一接口日志及接口响应时长

    内容概要:springboot+拦截器+aop+自定义注解+本地线程实现统一接口日志记录,记录下接口所在模块、接口描述、接口请求参数、接口返回参数、接口请求时间以及接口耗时用于接口优化,接口记录参数以及操作人防止使用...

    spring aop 实现源代码--xml and annotation(带lib包)

    在Spring1.2或之前的版本中,实现AOP的传统方式就是通过实现Spring的AOP API来定义Advice,并设置代理对象。Spring根据Adivce加入到业务流程的时机的不同,提供了四种不同的Advice:Before Advice、After Advice、...

    AOP事务所需要的jar包

    java项目中 AOP事务所需要用的jar包....................................啊..........................................................

    spring-aop-5.0.10.RELEASE-API文档-中文版.zip

    赠送jar包:spring-aop-5.0.10.RELEASE.jar; 赠送原API文档:spring-aop-5.0.10.RELEASE-javadoc.jar; 赠送源代码:spring-aop-5.0.10.RELEASE-sources.jar; 赠送Maven依赖信息文件:spring-aop-5.0.10.RELEASE....

    基于注解实现SpringAop

    基于注解实现SpringAop基于注解实现SpringAop基于注解实现SpringAop

    aop所依赖的所有包

    aop所依赖的所有包+文档+源码,最新版全套aop aspectjweaver aopalliance aspects aspectjrt

    反射实现 AOP 动态代理模式(Spring AOP 的实现原理)

    AOP的意思就是面向切面编程。本文主要是通过梳理JDK中自带的反射机制,实现 AOP动态代理模式,这也是Spring AOP 的实现原理

    spring aop jar 包

    spring aop jar 包

    aop面向切面需要的jar包

    在使用spring的aop功能时,这两个jar是必须的,否则会报错,如下: Caused by: java.lang.ClassNotFoundException: org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException at java.net....

    Spring_aop源码

    Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向方面的编程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何对象...

    AOP.in..NET

    AOP in .NET: Practical Aspect-Oriented Programming 296 pages Publisher: Manning Publications; Pap/Psc edition (June 25, 2013) Language: English ISBN-10: 1617291145 ISBN-13: 978-1617291142 ...

    SpringBoot下的SpringAOP-day04-源代码

    SpringBoot下的Spring——DAY04——动态代理总结、AOP、自定义注解进行拦截、动态获取注解参数、通知方法 1.动态代理总结 1.1 JDK动态代理特点 1.2 CGlib动态代理 1.2.1 CGLib特点说明 1.3 动态代理的作用 2 Spring...

Global site tag (gtag.js) - Google Analytics