第三章 AOP

第三章 AOP,第1张

简介

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程],通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

什么是OOP,Object Oriented Programming,原来就是面向对象的编程啊,还有OOD(面向对象的设计),OOA(面向对象的分析)

POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBeans,是为了避免和EJB混淆所创造的简称。

package com.demo.spring;
public class DbHello { //简单的Java类,称之为POJO,不继承,不实现接口
     private DictionaryDAO dao;
     public void setDao(DictionaryDAO dao) {
            this.dao = dao;
     }
} 

JavaBean

JavaBean实际上是指一种特殊的Java类,它通常用来实现一些比较常用的简单功能,并可以很容易的被重用或者是插入其他应用程序中去。所有遵循“一定编程原则”的Java类都可以被称作JavaBean。

JavaBean是一个遵循特定写法的Java类,是一种Java语言编写的可重用组件,它的方法命名,构造及行为必须符合特定的约定:

1、这个类必须具有一个公共的(public)无参构造函数;
2、所有属性私有化(private);
3、私有化的属性必须通过public类型的方法(getter和setter)暴露给其他程序,并且方法的命名也必须遵循一定的命名规范。
4、这个类应是可序列化的。(比如可以实现Serializable 接口,用于实现bean的持久性)

常用对象简称:

DAO :data access object 数据访问对象。

VO :value object 值对象 / view object 表现层(视图)对象。

DTO (TO) :Data Transfer Object 数据传输对象。

BO :business object 业务对象。

PO :persistent object持久对象。

6.1 AOP 基础概念

Aspect Oriented Programming(AOP)是较为热门的一个话题。AOP,国内大致译作“面向切面编程”。

“面向切面编程”,这样的名字并不是非常容易理解,且容易产生一些误导。有些人认为“OOP/OOD11即将落伍,AOP是新一代软件开发方式”。显然,发言者并没有理解AOP的含义。Aspect,的确是“方面”的意思。不过,汉语传统语义中的“方面”,大多数情况下指的是一件事情的不同维度、或者说不同角度上的特性,比如我们常说:“这件事情要从几个方面来看待”,往往意思是:需要从不同的角度来看待同一个事物。这里的“方面”,指的是事物的外在特性在不同观察角度下的体现。而在AOP中,Aspect的含义,可能更多的理解为“切面”比较合适。

可以通过预编译方式和运行其动态代理实现在不修改源代码的情况下给程序动态统一添加某种特定功能的一种技术。AOP实际是GoF设计模式的延续,设计模式孜孜不倦追求的是调用者和被调用者之间的解耦,提高代码的灵活性和可扩展性,AOP可以说也是这种目标的一种实现。

在Spring中提供了面向切面编程的丰富支持,允许通过分离应用的业务逻辑与系统级服务(例如审计(auditing)和事务(transaction)管理)进行内聚性的开发。应用对象只实现它们应该做的——完成业务逻辑——仅此而已。它们并不负责(甚至是意识)其它的系统级关注点,例如日志或事务支持。

主要功能

日志记录,性能统计,安全控制,事务处理,异常处理等等。

主要意图

将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。

6.2 AOP案例

添加aop常用的依赖包:aspectjweaver包,(javax.annotation-api是为了使用旧的init close方法)

6.2.1 配置方式

(1) aop功能实现的配置参考


<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans          
       http://www.springframework.org/schema/beans/spring-beans.xsd          
       http://www.springframework.org/schema/context          
       https://www.springframework.org/schema/context/spring-context.xsd   
       http://www.springframework.org/schema/aop          
       https://www.springframework.org/schema/aop/spring-aop.xsd">    
        
        
        
    
    <aop:config>
        <aop:pointcut id="stm" expression="execution(public * *(..))"/>
        <aop:pointcut id="sttt" expression="execution(public * org.beiyou.services.Student.s*(..))"/>
        <aop:aspect ref="db" id="db1">
            <aop:after method="close" pointcut-ref="sttt"/>
            <aop:before method="connect" pointcut-ref="stm"/>
        aop:aspect>
    aop:config>
    <bean id="st" class="org.beiyou.services.Student"/>
    <bean id="db" class="org.beiyou.services.Db"/>
beans>


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

<context:annotation-config/>
<context:component-scan base-package="com.zit.entity"/>
<aop:config>
    <aop:pointcut expression="execution(public * com.zit..*.save*(..))" id="cc"/>
    <aop:aspect ref="db">
        <aop:before method="connect" pointcut-ref="cc"/>
        <aop:after method="close" pointcut-ref="cc"/>
    aop:aspect>
aop:config>
beans>

第一步:pom.xml 添加依赖

<dependency>
    <groupId>org.aspectjgroupId>
    <artifactId>aspectjweaverartifactId>
    <version>1.9.7version>
dependency>

第二步:建立相关的类

Db.java

@Component
public class Db {
    public void connect() {
        System.out.println("Db.connect(数据库连接)");
    }

    public void close() {
        System.out.println("Db.close(关闭)");
    }
}

UserDao.java

@Component
public class UserDao {
    public int save(){
        System.out.println("执行了UserDao.save()数据保存");
        return 0;
    }

    public int saveUser(){
        System.out.println("执行了UserDao.saveUser()用户注册保存");
        return 0;
    }

    public int show(){
        System.out.println("执行了UserDao.show()");
        return 0;
    }

    public int delete(){
        System.out.println("执行了UserDao.delete()");
        return 0;
    }
}

BookDao.java

@Component
public class BookDao {
    public int save(){
        System.out.println("执行了BookDao.save()数据保存");
        return 0;
    }

    public int saveUser(){
        System.out.println("执行了BookDao.saveUser()用户注册保存");
        return 0;
    }

    public int show(){
        System.out.println("执行了BookDao.show()");
        return 0;
    }

    public int delete(){
        System.out.println("执行了BookDao.delete()");
        return 0;
    }
}

第三步:建立resources/beans.xml 配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">

    <content:component-scan base-package="cn.webrx.entity"/>
    <content:annotation-config/>

    <aop:config>
        
        <aop:pointcut expression="execution(public * cn.webrx..*Dao.s*(..))" id="cc"/>
        
        <aop:aspect ref="db">
            <aop:before method="connect" pointcut-ref="cc"/>
            <aop:after method="close" pointcut-ref="cc"/>
        aop:aspect>
    aop:config>

    <aop:config>
        
        <aop:pointcut expression="execution(public * cn.webrx..*Dao.d*(..))" id="dd"/>
        
        <aop:aspect ref="db">
            <aop:after method="close" pointcut-ref="dd"/>
        aop:aspect>
    aop:config>

beans>

第四步:编写主程序测试

/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn;

import cn.webrx.entity.BookDao;
import cn.webrx.entity.UserDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 

Project: spring - Demo *

Powered by webrx On 2021-07-02 11:12:12 *

Created by IntelliJ IDEA * * @author webrx [[email protected]] * @version 1.0 * @since 15 */ public class Demo { public static void main(String[] args) { var c = new ClassPathXmlApplicationContext("beans.xml"); var u = c.getBean(UserDao.class); u.save(); System.out.println("-".repeat(50)); u.saveUser(); System.out.println("-".repeat(50)); u.show(); u.delete(); var b = c.getBean(BookDao.class); b.save(); b.saveUser(); b.show(); b.delete(); //for(String s : c.getBeanDefinitionNames()){ // System.out.println(s); //} } }

6.2.2 注解编程方式

第一步:添加aop支持依赖

       <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.7version>
        dependency>

第二步:编写相关的bean

UserDao.java

/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.pojo;

import org.springframework.stereotype.Component;

/**
 * 

Project: spring - UserDao *

Powered by webrx On 2021-07-02 11:10:21 *

Created by IntelliJ IDEA * * @author webrx [[email protected]] * @version 1.0 * @since 15 */ @Component public class UserDao { public int save(){ System.out.println("执行了UserDao.save()数据保存"); return 0; } public int saveUser(){ System.out.println("执行了UserDao.saveUser()用户注册保存"); return 0; } public int show(){ System.out.println("执行了UserDao.show()"); return 0; } public int delete(){ System.out.println("执行了UserDao.delete()"); return 0; } }

Db.java

/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.pojo;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 

Project: spring - Db *

Powered by webrx On 2021-07-02 11:09:18 *

Created by IntelliJ IDEA * * @author webrx [[email protected]] * @version 1.0 * @since 15 */ @Component @Aspect public class Db { @Before("execution(public * cn.webrx.pojo..UserDao.s*(..))") public void connect() { System.out.println("Db.connect(数据库连接)"); } @After("execution(public * cn.webrx.pojo..*.save(..))") public void close() { System.out.println("Db.close(关闭)"); } @After("execution(public * cn.webrx.pojo..U*.s*(..))") public void cc() { this.close(); } }

@Aspect @Before("execution(public * cn.webrx.pojo..UserDao.s*(..))") @After("execution(public * cn.webrx.pojo..*.save(..))")

第三步:编写主程序配置类SpringApp.java

/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/**
 * 

Project: spring - SpringApp *

Powered by webrx On 2021-07-02 14:16:59 *

Created by IntelliJ IDEA * * @author webrx [[email protected]] * @version 1.0 * @since 15 */ @Configuration @ComponentScan("cn.webrx.pojo") @EnableAspectJAutoProxy public class SpringApp { }

@EnableAspectJAutoProxy

第四步:测试程序

public static void main(String[] args) {
        var ctx = new AnnotationConfigApplicationContext(SpringApp.class);
        var u = ctx.getBean(cn.webrx.pojo.UserDao.class);
        u.save();
        u.show();
        for (String s : ctx.getBeanDefinitionNames()) {
            System.out.println(s);
        }
    }
}

/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.pojo;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 

Project: spring2021 - Log *

Powered by webrx On 2021-11-02 17:49:21 *

Created by IntelliJ IDEA * * @author webrx [[email protected]] * @version 1.0 * @since 17 */ @Component @Aspect public class Log { @Before("execution(public * cn.webrx.pojo..Db.*(..)),execution(public * cn.webrx.pojo..User.*(..))") public void connect(){ System.out.println("Log.connect() 数据库连接"); } @After("execution(public * cn.webrx.pojo..*.*(..))") public void close(){ System.out.println("log(销毁连接)"); } }

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/737123.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存