zoukankan      html  css  js  c++  java
  • Spring配置AOP实现定义切入点和织入增强

    XML里的id=””记得全小写

    经过AOP的配置后,可以切入日志功能、访问切入、事务管理、性能监测等功能。

    首先实现这个织入增强需要的jar包,除了常用的

    com.springsource.org.apache.commons.logging-1.1.1.jar,

    com.springsource.org.apache.log4j-1.2.15.jar,

    spring-beans-3.2.0.RELEASE.jar,

    spring-context-3.2.0.RELEASE.jar,

    spring-core-3.2.0.RELEASE.jar,

    spring-expression-3.2.0.RELEASE.jar之外还需要

    spring-aop-3.2.0.RELEASE.jar,

    com.springsource.org.aopalliance-1.0.0.jar,(aop联合jar)

    com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar(织入方向jar)三个包。

    然后我有一个接口

    public interface Hello {

    public void say();

    }

    和一个实现类

    public class HelloImpl implements Hello{

    public void say(){

    System.out.println("执行say方法");

    }

    }

    和两个增强类

    前置增强:

    public class LogBefor implements MethodBeforeAdvice{

    @Override

    public void before(Method method, Object[] args, Object target)

    throws Throwable {

    System.out.println(method);

    System.out.println(args);

    System.out.println(target);

    }

    }

    后置增强:

    public class LogAfter implements AfterReturningAdvice{

    @Override

    public void afterReturning(Object returnValue, Method method,

    Object[] args, Object target) throws Throwable {

    System.out.println("返回值"+returnValue);

    System.out.println("方法:"+method);

    System.out.println("参数:"+args);

    System.out.println("被代理对象:"+target);

    }

    }

    接下来还需要在Spring配置文件中beans元素中需要添加aop的名称空间,以导入与AOP相关的标签:如:

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

             http://www.springframework.org/schema/aop

             http://www.springframework.org/schema/aop/spring-aop.xsd">   

    这里比之前的多了:xmlns:aop="http://www.springframework.org/schema/aop"

    在xsi:schemaLocation里多了两个

    http://www.springframework.org/schema/aop

    http://www.springframework.org/schema/aop/spring-aop.xsd;

    接下来在Spring配置文件中实现AOP配置,如我的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"

         xsi:schemaLocation="http://www.springframework.org/schema/beans

             http://www.springframework.org/schema/beans/spring-beans.xsd

             http://www.springframework.org/schema/aop

             http://www.springframework.org/schema/aop/spring-aop.xsd">

             

    <bean id="hello" class="cn.cnti.aop.HelloImpl"></bean>

     

    <!-- 增强类 -->

    <bean id="before" class="cn.cnti.aop.LogBefor">

    </bean>

    <bean id="after" class="cn.cnti.aop.LogAfter">

    </bean>

     

    <aop:config>

    <!-- 定义切入点 -->

             <aop:pointcut id="pointcut"

                        expression="execution(public void say())"/>

             <aop:advisor advice-ref="before" pointcut-ref="pointcut"/>

             <aop:advisor advice-ref="after" pointcut-ref="pointcut"/>

       </aop:config>

     </beans> 

    如果记不清楚的话,spring-framework-3.2.0.RELEASE-distspring-framework-3.2.0.RELEASEdocsspring-framework-referencehtmlaop.html打开后搜索aop会有模板。

    其中execution是切入点指示符,它的括号中是一个切入点表达式,可以配置要切入的方法,切入点表达式支持模糊匹配:

    Public * say(entity.User):”*”表示匹配所有类型的返回值

    Public void *(entity.User):”*”表示匹配所有方法名。

    Public void say(..):”..”表示匹配所有参数个数和类型。

    * cn.jnti.service.*.*(..):这个表达式匹配cn.jnti.service包下所有类的所有方法。

    * cn.jnti.service..*.*(..):这个表达式匹配cn.jnti.service包及其子包下所有类的所有方法。

    等等,还有许多。

    最后我们测试一下:

    @Test

    public void mtest(){

    BeanFactory bf=new  ClassPathXmlApplicationContext("appContext.xml");

    Hello h = (Hello) bf.getBean("hello");

    h.say();

    }

     ***********************************************************************************************************

    如果想实现日志输出的话,在这个原有jar包的基础上需要

    cglib-nodep-2.2.3.jarorg.springframework.asm-3.1.1.RELEASE.jar

    然后再前置增强和后置增强里各加一个静态常量:

    Private static final Logger log=Logger.getLogger(LogBefor.class);

    Private static final Logger log=Logger.getLogger(LogAfter.class);

    然后在方法里直接用lo.info(“调用”+target6”的”+method.getName()+”方法”+”参数是:”+Arrays.toString(args));就行了。

    *****************************************************************************************************************************************

    环绕增强:

    首先有一个一个User类里面有name,price属性。

    有一个接口:

    public interface UserService {

     Object save(User user);

    }

    有一个实现类:

    public class UserServiceImpl implements UserService {

    @Override

    public Object save(User user) {

    System.out.println(user.getName()+"存了"+user.getPrice()+"$");

    return true;

    }

    }

    我的循环增强类实现MethodInterceptor(是在importorg.aopalliance.intercept.MethodInterceptor包下):

    import org.aopalliance.intercept.MethodInterceptor;

    import org.aopalliance.intercept.MethodInvocation;

     

    public class Surround implements MethodInterceptor{

     

    @Override

    public Object invoke(MethodInvocation arg0) throws Throwable {

    System.out.println("我进循环增强了!");

    Object[] objects = arg0.getArguments();

    for (Object obj : objects) {

    System.out.println(obj);

    }

    User user=(User) objects[0];

    if(user.getPrice()<0){

    System.out.println("存款不能为负数!");

    return false;

    }else{

    //放行

    return arg0.proceed();

    }

    }

    }

    我的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"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

             http://www.springframework.org/schema/beans/spring-beans.xsd

             http://www.springframework.org/schema/aop

             http://www.springframework.org/schema/aop/spring-aop.xsd">

     

    <bean id="usersericeimpl" class="cn.cnti.aop.UserServiceImpl">

    </bean>

    <bean id="surround" class="cn.cnti.aop.Surround"></bean>

    <!-- 增强类 -->

    <aop:config>

    <!-- 定义切入点 -->

    <aop:pointcut id="pointcut" expression="execution(* cn.cnti.aop..*.*(..))" />

    <aop:advisor advice-ref="surround" pointcut-ref="pointcut" />

    </aop:config>

    我的测试类:

    @Test

    public void testAround(){

    BeanFactory bf=new ClassPathXmlApplicationContext("appContext.xml");

    UserService us= (UserService) bf.getBean("usersericeimpl");

    Object object = us.save(new User("sp",101));

    System.out.println(object);

    }

     ***********************************************************************************************************

    异常抛出增强:

    只需要有一个类实现ThrowsAdvice接口:

    import java.lang.reflect.Method;

    import org.springframework.aop.ThrowsAdvice;

    public class ErrorLogger implements ThrowsAdvice{

    public void afterThrowing(Method method,Object[] args,Object target,Exception e){

    System.out.println("调用"+target+"的"+method.getName()+"方法时,发生异常"+e);

    }

    }

    ,但是

    通过ThrowsAdvice接口实现异常抛出增强。ThrowsAdvice接口中并没有定义任何方法。

    但是我们在定义异常抛出的增强方法时必须遵守以下方法签名。

    afterThrowing(Method method,Object[] args,Object target,Exception e)

    这里规定了方法名必须是afterThrowing。方法的入参只有最后一个是必须的,前三个入参是可选的,

    但是前3个参数要么都提供,要么一个也不提供。

    然后在xml配置里再加上:

    <!-- 异常抛出增强 -->

    <bean id="errorlogger" class="cn.cnti.aop.ErrorLogger"></bean>

    <aop:config>

    <!-- 定义切入点 -->

    <aop:pointcut id="pointcut" expression="execution(* cn.cnti.aop..*.*(..))" />

    <aop:advisor advice-ref="errorlogger" pointcut-ref="pointcut" />

    </aop:config>

    因为没有异常的话是不会看到效果的,所以要手动制造一个异常:

    public Object save(User user) {

    System.out.println(user.getName()+"存了"+user.getPrice()+"$");

    int a=1/0;

    return true;

    }

    ******************************************************************************************************

    使用注解标注增强:

    我的注解增强类:

    package cn.cnti.annotation;

     

    import org.aspectj.lang.annotation.AfterReturning;

    import org.aspectj.lang.annotation.Aspect;

    import org.aspectj.lang.annotation.Before;

    //@Aspect注解将UserBizAdvice定义为切面

    @Aspect

    public class UserBizAdvice{

    //前置增强

    @Before("execution(* cn.cnti.annotation..*.*(..))")

    public void before(){

    System.out.println("即将调用业务方法!");

    }

    //后置增强

    @AfterReturning("execution(* cn.cnti.annotation..*.*(..))")

    public void afterReturning(){

    System.out.println("后置增强");

    }

    }

    配置文件除了要导入aop命名空间外,只需要在配置文件中添加

    <aop:aspectj-autoproxy />元素,即可启用对于@AspectJ注解的支持,Spring将自动为匹配的Bean创建代理,为了注册定义好的切面,还要在Spring配置文件中声明UserBizAdvice的一个实例(不需要被其他Bean引用,可以不指定Id属性);

    我的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.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context.xsd

    http://www.springframework.org/schema/aop

     http://www.springframework.org/schema/aop/spring-aop.xsd

    ">

    <bean id="userserviceimpl" class="cn.cnti.annotation.UserServiceImpl"></bean>

    <aop:aspectj-autoproxy />

    <bean class="cn.cnti.annotation.UserBizAdvice"></bean>

     ****************************************************************************************************************

    </beans>

    上一个注解标注增强还可以这么用:

    @Aspect//@Aspect注解将UserBizAdvice定义为切面

    public class UserBizAdvice2{

    @Pointcut("execution(public void save(..))")

    public void cut(){

    }

     

    //前置增强

    @Before("cut()")

    public void before(){

    System.out.println("wo shi UserBizAdvice2");

    System.out.println("即将调用业务方法!");

    }

    //后置增强

    @AfterReturning("cut()")

    public void afterReturning(){

    System.out.println("wo shi UserBizAdvice2");

    System.out.println("后置增强");

    }

    }

    其他不变!

    ***************************************************************************************************************

    使用注解定义其他类型的增强:

    我的注解增强类:

    @Aspect//@Aspect注解将UserBizAdvice定义为切面

    public class UserBizAdvice2{

    @Pointcut("execution(public void save(..))")

    public void cut(){

    }

     

    //前置增强

    @Before("cut()")

    public void before(JoinPoint jp){

    System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法入参:"+Arrays.toString(jp.getArgs()));

    System.out.println("前置增强");

    }

    //后置增强

    @AfterReturning(pointcut="cut()",returning="returnValue")

    public void afterReturning(JoinPoint jp,Object returnValue){

    System.out.println("返回值是:"+returnValue);

    System.out.println("后置增强");

    }

     

    @AfterThrowing(pointcut="cut()",throwing="ex")

    public void afterThrowing(JoinPoint jp,Exception ex){

    System.out.println("异常了:"+ex);

    }

    //ProceedingJoinPoint是JoinPoint的子接口,它的proceed()方法可以调用真正的目标方法,从而达到对连接点的完全控制

    @Around("cut()")

    public Object around(ProceedingJoinPoint pjp) throws Throwable{

    System.out.println("环绕前");

    Object obj = pjp.proceed();

    System.out.println("环绕后");

    return obj;

    }

    //@AspectJ还提供了一种最终增强类型,其特点是无论方法抛出异常还是正常退出,该增强都会得到执行,类似于异常处理机制中finally块的作用,一般用于释放资源。

    @After("cut()")

    public void after(){

    System.out.println("最终增强!");

    }

    }

    XML同上一个XML没有变化,唯一注意的一点是:<aop:aspectj-autoproxy />

    自动代理默认是对接口的代理,我们测试的时候:

    BeanFactory bf=new ClassPathXmlApplicationContext("annotationContext.xml");

    UserService  service = (UserService) bf.getBean("userserviceimpl");

    service.save(new User("admin","pwd"));

    都是强转成接口,然后用接口接受,

    如果想对类进行代理,可以这么设置:

    <aop:aspectj-autoproxy proxy-target-class="true"/>

    *****************************************************************************************************************

    使用Schema配置其他增强类型:

    我的增强类:

    public class UserBizAdvice {

    public void before(JoinPoint jp){

    System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法入参:"+Arrays.toString(jp.getArgs()));

    System.out.println("前置增强");

    }

    public void afterReturning(JoinPoint jp,Object returnValue){

    System.out.println("返回值是:"+returnValue);

    System.out.println("后置增强");

    }

     

    public void afterThrowing(JoinPoint jp,Exception ex){

    System.out.println("异常了:"+ex);

    }

     

    public Object around(ProceedingJoinPoint pjp) throws Throwable{

    System.out.println("环绕前");

    Object obj = pjp.proceed();

    System.out.println("环绕后");

    return obj;

    }

    public void after(){

    System.out.println("最终增强!");

    }

    }

    然后我的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.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context.xsd

    http://www.springframework.org/schema/aop

     http://www.springframework.org/schema/aop/spring-aop.xsd

    ">

    <bean id="userserviceimpl" class="cn.cnti.schema.UserServiceImpl"></bean>

    <bean id="advice" class="cn.cnti.schema.UserBizAdvice"></bean>

    <aop:config>

    <aop:pointcut expression="execution(* cn.cnti.schema..*.*(..))" id="pointcut"/>

    <aop:aspect ref="advice">

    <aop:before method="before" pointcut-ref="pointcut"/>

    <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="returnValue"/>//和类里的Object returnValue对应

    <aop:after method="after" pointcut-ref="pointcut"/>

    <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"/>

    <aop:around method="around" pointcut-ref="pointcut"/>

    </aop:aspect>

    </aop:config>

    </beans>

  • 相关阅读:
    关于如何使用Microsoft Word发博客
    TEST
    信息安全系统设计基础第三周学习总结
    信息安全系统设计基础第一周学习总结
    Java程序设计实验 实验五
    实验三 敏捷开发与XP实践 实验报告
    git 连接github的配置
    nginx是什么,如何使用
    spring-boot 全面认知
    删除指定目录文件夹下的文件
  • 原文地址:https://www.cnblogs.com/345214483-qq/p/4178638.html
Copyright © 2011-2022 走看看