5.Spring中的AOP

AOP的定义

AOP基本上是通过代理机制实现的,他是OOP的延续也是spring框架中最重要的内容之一.

  • 定义:运行时,动态地将代码切入到类的指定方法、指定位置上的编程思想就是面向切面的编程.
  • 使用场景:日志、事务、缓存、调试等

AOP中基本概念

  • Aspect(切面):将关注点进行模块化.
  • Join Point(连接点):在程序执行过程中的某个特定的点,如谋方法调用时或处理异常时.
  • Advice(通知):在切面的某个特定的连接点上执行的动作.
  • PointCut(切入点):匹配连接点的断言.
  • Introduction(引入):声明额外的方法或某个类型的字段.
  • Target Object(目标对象):被一个或多个切面所通知的对象.
  • AOP Proxy(AOP代理):AOP框架创建的对象,用来实现Aspect Contract包括通知方法执行等功能.
  • Weaving(织入):把切面连接到其他的应用程序类型或对象上,并创建一个Advice的对象.

AOP代理

Spring AOP默认使用标准的JDK动态代理来作为AOP的代理,这样任何接口都可以被代理.

  • 使用AspectJ
    配置为:
<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
</dependency>
  • 实际应用
public interface Hello {
    String getHellow();
}
public class HelloImpl implements Hello{
    @Override
    public String getHellow() {
        return "Hello,spring AOP";
    }
}
public class MyBeforeAdvice {
    private static final Logger logger= LoggerFactory.getLogger(MyBeforeAdvice.class);

    //定义前置方法
    public void beforeMethod(){
        logger.info("this is a pig");
//        System.out.println("this is a before method.");
    }
}
       <bean id="hello" class="com.spring.aop.HelloImpl"/>
       <bean id="myBeforeAdvice" class="com.spring.aop.MyBeforeAdvice"/>
      <!--配置aop-->
       <aop:config>
           <aop:aspect id="before" ref="myBeforeAdvice">
               <aop:pointcut id="myPointCut" expression="execution(* com.spring.aop.*.*(..))"/>
               <aop:before method="beforeMethod" pointcut-ref="myPointCut"/>
           </aop:aspect>
       </aop:config>
public class HelloApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
        Hello hello = context.getBean(Hello.class);
        System.out.println(hello.getHellow());
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • IoC 容器 Bean 的作用域 自定义作用域实现 org.springframework.beans.facto...
    Hsinwong阅读 2,517评论 0 7
  • 本章内容: 面向切面编程的基本原理 通过POJO创建切面 使用@AspectJ注解 为AspectJ切面注入依赖 ...
    谢随安阅读 3,214评论 0 9
  • 概述 Spring是什么? Spring是一个开源框架,为了解决企业应用开发的复杂性而创建的,但是现在已经不止于企...
    琅筑阅读 1,207评论 2 8
  • 因为工作需求,自己去了解一下aop并做下的记录,当然大部分都是参考他人博客以及官方文档。 目录 [关于 AOP](...
    forip阅读 2,292评论 1 20
  • “呼呼……”风不停地拍打着窗户,好似一只大老虎撕咬着世间万物。大树都低下了头,像一个犯错的小孩。枯黄的树...
    小罗琳阅读 134评论 0 1