`

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-...

    aop所依赖的所有包

    AOP(Aspect-Oriented Programming,面向切面编程)是一种编程范式,旨在减少代码的重复性和增强可维护性,特别是在处理系统中的横切关注点时。这些关注点,如日志、事务管理、安全检查等,往往分散在系统的各个部分...

    aopalliance-1.0.jar及aopalliance源码

    **AOP Alliance简介** AOP Alliance是一个开源项目,它的全称是Aspect Oriented Programming(面向切面编程)Alliance,是Java平台上的一个接口集合,为面向切面编程的实现提供了一个统一的API。这个库的主要目的是...

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

    面向切面编程(AOP)是一种编程范式,旨在将横切关注点(如日志、安全等)与业务逻辑分离,从而提高模块化。AOP通过预定义的“切面”对横切关注点进行模块化,从而可以在不修改业务逻辑代码的情况下增加新功能。动态...

    spring aop jar 包

    Spring AOP(Aspect Oriented Programming,面向切面编程)是Spring框架的重要组成部分,它提供了一种在不修改源代码的情况下,对程序进行功能增强的技术。这个"spring aop jar 包"包含了实现这一功能所需的类和接口,...

    aopalliance最新完整jar包

    在Java应用中,aopalliance.jar包扮演着至关重要的角色,它包含了一些核心接口,如`org.aopalliance.intercept.MethodInterceptor`和`org.aopalliance.aop.Advice`,这些接口定义了拦截器和通知的概念,它们是AOP的...

    spring-boot aop

    Spring Boot AOP(面向切面编程)是一种强大的设计模式,它允许我们在不修改现有代码的情况下,插入额外的功能或监控代码。在Spring框架中,AOP主要用于日志记录、事务管理、性能统计等场景。本示例是关于如何在...

    springAOP所依赖的jar包

    Spring AOP(面向切面编程)是Spring框架的重要组成部分,它允许程序员定义“切面”,这些切面可以封装跨越多个对象的行为或责任。在Java应用中实现AOP通常需要依赖于一些外部库,这些库在你提供的标题和描述中有所...

    利用C#实现AOP常见的几种方法详解

    面向切面编程(AOP,Aspect Oriented Programming)是一种编程范式,旨在通过将关注点分离,使得系统设计更加模块化。AOP的核心思想是将应用程序的横切关注点(如日志、事务管理、安全检查等)从核心业务逻辑中解耦...

    aop开发环境jar包

    在IT行业中,AOP(Aspect-Oriented Programming,面向切面编程)是一种编程范式,它旨在提高软件的模块化程度,将关注点分离。在Java世界里,AOP常用于处理日志、事务管理、权限检查等横切关注点。当我们谈到“AOP...

    spring-aop-jar

    在IT领域,Spring框架是一个广泛使用的Java应用框架,它提供了许多功能,包括依赖注入、面向切面编程(AOP)等。"spring-aop-jar"这个主题涉及到Spring框架中的核心组件之一——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 spring aop

    在给出的XML配置中,`&lt;aop:config&gt;`元素开启AOP支持,而`&lt;aop:aspect&gt;`元素用于定义切面,其内部通过`&lt;aop:pointcut&gt;`定义切点,并通过`&lt;aop:before&gt;`和`&lt;aop:after&gt;`指定通知。 为了使用这些配置,我们需要在代码...

    C#版本AOP注入

    在IT行业中,面向切面编程(Aspect-Oriented Programming,简称AOP)是一种设计模式,它旨在提高软件的模块化程度,将关注点分离,使业务逻辑与系统服务(如日志、事务管理、安全控制等)解耦。C#作为.NET框架的主要...

    springAop与spring定时器

    Spring AOP(面向切面编程)是Spring框架中的一个重要组件,它允许我们在不修改源代码的情况下,通过在程序运行时动态地将代码插入到方法调用中,来实现跨切面的关注点,如日志记录、性能监控、事务管理等。...

    C# .net Aop 动态截获异常

    在.NET开发环境中,C#语言提供了丰富的特性(Attributes)、依赖注入(DI)和面向切面编程(AOP)等机制,使得我们可以构建更加灵活、可维护的代码。本主题将深入探讨如何使用C#和AOP来动态截获异常,以实现更高级别...

    Spring使用AOP的三个jar包

    最后,`aopalliance-1.0.0.jar`是AOP联盟提供的一个接口库,它定义了一些通用的AOP接口,比如`org.aopalliance.intercept.MethodInterceptor`和`org.aopalliance.intercept.MethodInvocation`,使得不同的AOP框架...

    aop@work.rar

    《面向切面编程(AOP)的工作原理与实践》 面向切面编程(Aspect-Oriented Programming,简称AOP)是软件开发中的一个重要概念,它旨在解决程序中的横切关注点,即那些跨越多个模块、类或方法的共同功能,如日志、...

    aopalliance-1.0.jar下载

    《aopalliance-1.0.jar:AOP联盟的核心库解析》 在Java开发领域,面向切面编程(Aspect-Oriented Programming, AOP)是一种重要的编程范式,它旨在将关注点分离,使系统设计更为模块化,降低耦合度。而aopalliance-...

    Spring中的AOP不生效

    ### Spring中的AOP不生效的原因及解决方法 在Java开发中,面向切面编程(Aspect Oriented Programming,简称AOP)是一种重要的编程思想和技术手段,主要用于处理横切关注点问题,如日志记录、性能统计、安全控制、...

Global site tag (gtag.js) - Google Analytics