spring框架学习 使用注解的AOP开发

注解的类型

通知的配置语法:@通知注解("切点表达式")

  1. 前置通知 @Before 用于配置前置通知。指定增强的方法在切入点方法之前执行
  2. 后置通知 @AfterReturning 用于配置后置通知。指定增强的方法在切入点方法之后执行
  3. 环绕通知 @Around 用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行
  4. 异常抛出通知 @AfterThrowing 用于配置异常抛出通知。指定增强的方法在出现异常时执行
  5. 最终通知 @After 用于配置最终通知。无论增强方式执行是否有异常都会执行

注解AOP的开发步骤测试

① 使用@Aspect标注切面类
② 使用@通知注解标注通知方法
③ 在配置文件中配置aop自动代理<aop:aspectj-autoproxy/>

1、目标对象接口与实现接口类

public interface targetInterface {
    void save();
    void delete();
}

@Component("target")
public class target implements targetInterface {
    @Override
    public void save() {
        System.out.println("目标对象的功能save执行.....");
    }
    @Override
    public void delete() {
        System.out.println("目标对象的功能delete执行.....");
    }
}

2、切面类

 //切面类
    @Component("myAspect")
    @Aspect
    public class myAspect {

        @Before("execution(public void com.hlc.aop.target.save())")
        public void before(){
            System.out.println("前置增强....");
        }
        @AfterReturning("execution(public void com.hlc.aop.target.delete())")
        public void after(){
            System.out.println("后置增强....");
        }
 
        @After("execution(public void com.hlc.aop.target.delete())")
        public void bye(){
            System.out.println("增强结束....");
        }

        @Around("execution(public void com.hlc.aop.target.save())")
        public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            System.out.println("环绕保护进程....");
            Object proceed = proceedingJoinPoint.proceed();
            System.out.println("运行完毕!保护结束....");
            return proceed;
        }
    }

3、xml配置AOP自动代理与组件扫描

<!--    aop的自动代理,通常结合组件扫描context一起使用于aop的注解开发-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <context:component-scan base-package="com.hlc.aop"/>
</beans>

4、测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-aop.xml")
public class aopTest {
    @Autowired
    private targetInterface target;
    @Test
    public void test1(){
        target.save();
    }
    @Test
    public void test2(){
        target.delete();
    }
}

5、测试结果

 

 在前面我们对于springIOC的DI注入的学习过程中,关于xml文件的标签属性特点有了很深的记忆性,注解肯定是好用的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ForestSpringH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值