xml与注解配置AOP开发的步骤

xml与注解配置AOP开发的步骤,第1张

xml与注解配置AOP开发的步骤

xml方式:

1.建立目标方法(切点)以及通知(即方法)

2.建立xml文件

2.1配置

xmlns:aop="http://www.springframework.org/schema/aop"
以及
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd

2.2 配置目标对象、

2.3配置切面对象

2.4配置织入,告诉spring哪些方法需要增强

        
        
            
            
            
            


            
            

        
    

3.测试类 注解:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")

注解说明(搬运内容,若侵权请告知后删除):

    1)@RunWith:用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境。

    2)@ContextConfiguration({"classes=Congfig.clsss",classpath:applicationContext.xml"}) 这里可以用classes来直接导入同包下写的配置类。或者导入配置文件。

注解方式配置AOP

1.配置xml文件

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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">

1.2开启组件扫描和aop自动代理(组件扫描是为了扫到目标方法即切点)

    

    
    

2.建立目标方法(需要执行的方法)和切面类(通知内容)

2.1 对于目标方法只需要加上(在测试类中能被扫到以及识别即可)

@Component("xxx")

2.2对于切面类不同的通知对应不同的注解 (在类的上方注解该类位切面类)

@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面类
public class MyAspect {


    //配置前置通知
    @Before("execution(* com.it.anno.*.*(..))")
    public void before(){
        System.out.println("前置...");
    }

    public void afterRunning(){
        System.out.println("后置...");
    }


    //@Around("execution(* com.it.anno.*.*(..))")
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前增强");
        Object proceed = pjp.proceed();//切点方法
        System.out.println("环绕后增强");
        return proceed;
    }

    public void afterThrowing(){
        System.out.println("异常增强");
    }

    //@After("execution(* com.it.anno.*.*(..))")
    @After("MyAspect.pointcut()")
    public void after(){
        System.out.println("最终增强");
    }

    //定义切点表达式
    @Pointcut("execution(* com.it.anno.Target.save())")
    public void pointcut(){}
}

3.测试类 同xml

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5722019.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存