初学Spring04

使用Spring AOP代理

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")
public class AopTest {

    @Autowired
    private TargetInterface target;

    @Test
    public void test1(){
        target.save();
    }

}
     <aop:config>
        <aop:aspect ref="myAspect">
<!--            <aop:before method="beforeSave" pointcut="execution(public void com.qing.aop.*.*(..))"></aop:before>-->
<!--            <aop:after method="afterSave" pointcut="execution(public void com.qing.aop.Target.save())"></aop:after>-->
            <aop:pointcut id="myPointcut" expression="execution(public void com.qing.aop.*.*(..))"/>
            <aop:around method="around" pointcut-ref="myPointcut"></aop:around>
            <aop:after-throwing method="afterThrowing" pointcut-ref="myPointcut"></aop:after-throwing>
            <aop:after-returning method="afterReturning" pointcut-ref="myPointcut"></aop:after-returning>
            <aop:after method="after" pointcut-ref="myPointcut"></aop:after>
        </aop:aspect>
    </aop:config>

在这里插入图片描述
注解开发

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

    @Before("pointcut()")
    public static void beforeSave(){
        System.out.println("前置增强");
    }

    @AfterReturning("pointcut()")
    public static void afterReturning(){
        System.out.println("后置增强");
    }

    @After("pointcut()")
    public static void after(){
        System.out.println("最终增强");
    }

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

    @AfterThrowing("pointcut()")
    public static void afterThrowing(){
        System.out.println("异常!!!");
    }


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



}

如果用SpringJunit集成,@RunWith(SpringJUnit4ClassRunner.class)有这个注解,就必须用注解配置configuration文件

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值