Spring基本原理之IOC和AOP

一、IOC(Inversion Of Control)

In software engineering, inversion of control (IoC) is a programming principle. IoC inverts the flow control as compared to traditional control flow. In IoC, custom-written portions of a computer program receive the flow of control from a generic framework. A software architecture with this design inverts control as compared to traditional procedural programming: in traditional programming, the custom code that expresses the purpose of the program calls into reusable libraries to take care of generic tasks, but with inversion of control, it is the framework that calls into the custom, or task-specific, code.(from wikipedia)

       相对于传统的控制流,把创建对象获取实例的过程交给了IOC容器,并由其管理对象的生命周期,达到复用和解耦的目的。

       何为反转?容器帮助查找和注入对象,对象从主动创造变成了被动依赖,称之为传统意义上的反转。

       常用的方式是DI(Dependency Injection)即依赖注入,还有一种是DL(Dependency Lookup),因为前者用的比较多,常被误解IOC就是DI。

控制反转

  • DI(依赖注入)

       有两种方式:Setter方式(传值方式)和构造器方式(引用方式)。组件之间的依赖关系由容器在应用系统运行期来决定,也就是由容器动态地将某种依赖关系的目标对象实例注入到应用系统中的各个关联的组件之中。

  • DL(依赖查找)
           有两种方式:依赖拖拽(DP)和上下文依赖查找(CDL)。依赖拖拽需要依托于xml来管理bean,而上下文则是从容器里查找。

有趣的比喻:男女找对象。在IOC之前,就像男女自由恋爱,谈朋友需要自己主动去表白约会……过程自己控制;而IOC之后,就像在某红娘网站注册会员,他们管理了很多单身男女信息,然后他们会推给你喜欢的类型,如果对象不合适会抛出异常,这不用我们操心全程有红娘系统处理。

二、AOP(Aspect Oriented Programming)

In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a “pointcut” specification, such as “log all function calls when the function’s name begins with ‘set’”. This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code, core to the functionality. AOP forms a basis for aspect-oriented software development.(from wikipedia)

       AOP技术恰恰相反,它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。

  • 横切关注点

       拦截的方法和处理方式

  • 切面(Aspect)

       对横切关注点的抽象

  • 连接点(JoinPoint)

       Spring只支持方法型的连接点,而实际的连接点还可以是字段或者构造器

  • 切入点(PointCut)

       对连接点进行拦截的定义

  • 通知(Advice)

       拦截到连接点后需要执行的代码,通知分为:前置(before),后置(after),异常(afterThrowing),最终(afterReturning),环绕(around)五类

  • 目标对象

       代理的目标对象

  • 织入(Weave)

       将切面应用到对象,使得代理对象创建的过程:进入目标方法,先织入around,再织入before,退出目标方法时,先植入around,在织入afterReturning,最后才织入after。并且环绕通知会影响afterThrowing,一般不同时使用。

  • 引入(Introduction)

       在不修改代码的前提下,引入可以在运行期为类动态添加方法或者字段

おすすめ

転載: blog.csdn.net/CUG_ZG/article/details/87743258