七、AOP面向方面-Spring快速入门小白编

使用注解实现通知
jar包:
aspectjweaver-1.9.5

配置文件applicationContext.xml

<!--        配置扫描器 扫描包内的@Component等注解,用于注入ioc-->
    <context:component-scan base-package="com.bb"></context:component-scan>
    <!--    开启AOP的注解支持,能够使用@Aspect注解-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

在类前增加注解@Component:将该类注入ioc容器
在类前增加注解@Aspect:表明此类是一个通知
在方法前增加注解@Before("execution(xxx)"):表明在xxx方法前执行该方法

通知类(切面类)LogBefore.java

package com.bb.service;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component("logAnnotation")
@Aspect  //定义该类为一个通知
public class logBefore{
    @Before("execution(public * addStudent())")
    public void myBefore(){
        System.out.println("注解形式的前置通知");
    }
}

调用方法所在类(切入点类)AddService.java

package com.bb.service;
import org.springframework.stereotype.Component;

@Component("addservice")
public class AddService {
    public  void addStudent(){
        System.out.println("增加一个学生");
    }
}

测试类

    public static void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AddService addservice = (AddService) context.getBean("addservice");
        addservice.addStudent();
    }

结果输出:

注解形式的前置通知
增加一个学生

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容