Spring框架基于注解的AOP使用

Spring框架基于注解的AOP使用

注解相对于xml的使用来说比较方便,但是维护相对来说会比较难,如果我们需要改动,假设类特别多的时候改动就需要很大的精力,但是xml的相对维护简单。

使用注解开发(导入相关jar,和aspectj包)
1.我们需要一个注解配置类,需要有@Configuration来表明这个是注解类,@ComponentScan来扫描类在IOC容器里面创建对象由Spring容器来管理,@EnableAspectJAutoProxy用于扫描是否有通知类,通知类通常会有@Aspect注解表示我是通知类
2.创建实体对象和通知类,别忘了加上注解
3.测试类

代码(注解类配置)

@Configuration
@EnableAspectJAutoProxy
@ComponentScan(value = "JDKProxy.book")
public class XMLProxy {
}

代码(实体类)

@Component
public class Teacher {
    public void teach(){
        System.out.println("教授....");
    }

    public void test(){
        System.out.println("测试....");
    }
}

代码(通知类)

@Component
@Aspect
public class TeacherProxy {
    @Pointcut("execution(* JDKProxy.book.Teacher.test())")
    public void ponintCutTest(){

    }

    @Before("ponintCutTest()")
    public void checkScore(){
        System.out.println("改卷....");
    }


    @Pointcut("execution(* JDKProxy.book.Teacher.teach(..))")
    public void pointCutLocation(){

    }

    @Before("pointCutLocation()")
    public void before(){
        System.out.println("before");
    }

    @After("pointCutLocation()")
    public void after(){
        System.out.println("after...");
    }

    @AfterReturning("pointCutLocation()")
    public void afterReturning(){
        System.out.println("AfterReturning...");
    }

    @Around("pointCutLocation()")
    public void around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("环绕前....");
        point.proceed();
        System.out.println("环绕后");
    }

代码(测试类)

 @Test
    public void test4(){
        ApplicationContext context=new AnnotationConfigApplicationContext(XMLProxy.class);
        Teacher teacher = context.getBean("teacher", Teacher.class);
        teacher.teach();
        teacher.test();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值