Spring学习(四)Spring AOP 简介

一、简介

定义

 aop就是面向切面编程,在数据库事务中切面编程被广泛使用。

 在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能

 核心业务:比如登陆,增加数据,删除数据都叫核心业务

 周边功能:比如性能统计,日志,事务管理等等

 PS:在 Spring 面向切面编程的AOP思想里,周边功能即被定义为切面

核心思想

  核心业务功能和切面功能分别独立进行开发,然后把切面功能和核心业务功能 "编织" 在一起,这就叫AOP。

目的

  是将那些与业务无关,却被业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来,便于减少系统的重复代码降低模块间的耦合度,并有利于未来的可拓展性和可维护性

相关概念

切入点(Pointcut)

  在哪些类,哪些方法上切入(where

通知(Advice)

  在方法执行的时机(when:方法前/方法后/方法前后)做什么(what:增强的功能),包括 “around,” “before” and "after"等多种类型。

切面(Aspect)

  切面 = 切入点 + 通知,通俗点就是:在什么时机,什么地方,做什么增强!

织入(Weaving)

  把切面加入到对象,并创建出代理对象的过程。(由 Spring 来完成)

代码分析

1、新建一个类(功能:模拟业务功能代码)

/**
 * 模拟正式的业务service
 */
public class ProductService {
    public void doSomeService(){
        System.out.println("doSomeService");//模拟正式业务
    }
}

2、新建一个切面(功能:模拟日志记录)

/**
 * 定义一个切面(功能:模拟记录日志)
 */
public class LoggerAspect {

  //入参可以理解为相应的核心业务,方法内代码操控核心业务在这个切面中怎么处理(下面的功能实现了在核心业务的前后分别打印两行语句)
public Object log(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("start log:" + joinPoint.getSignature().getName()); Object object = joinPoint.proceed(); System.out.println("end log:" + joinPoint.getSignature().getName()); return object; } }

3、xml配置刚才新增的两个bean,再对AOP进行配置

    <!--配置一个名叫productService的bean,这个service功能是模拟正式业务的代码-->
    <bean name="productService" class="service.ProductService"/>

    <!--配置日志bean-->
    <bean id="loggerAspect" class="aspect.LoggerAspect"/>
    
    <!--配置AOP切面-->
    <aop:config>
        <!-- 配置切入点 expression属性设置切点表达式(AspectJ) -->
        <aop:pointcut id="loggerCutpoint" expression="execution(* service.ProductService.*(..)) "/>
        <!-- 配置切面(增加日志功能) -->
        <aop:aspect id="logAspect" ref="loggerAspect">
            <!-- 配置切面切入时机  around表示在核心业务功能前后执行切面  method表示要调用的方法-->
            <aop:around pointcut-ref="loggerCutpoint" method="log"/>
        </aop:aspect>
    </aop:config>

4、测试代码

        //1、使用ApplicationContext类读取xml配置文件生成bean工厂(bean工厂为了控制反转时获取对象用)
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[]{"applicationContext.xml"}
        );

        //4、查看切面的实现结果
        ProductService productService = (ProductService)context.getBean("productService");
        productService.doSomeService();

5、显示结果

 

posted @ 2019-09-11 16:06  有梦想的肥宅  阅读(299)  评论(0编辑  收藏  举报