SpringAOP 面向切面编程

AOP的相关概念

AOP:全称是 Aspect Oriented Programming 即:面向切面编程。

简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的
基础上,对我们的已有方法进行增强。

AOP 的作用及优势

作用:
在程序运行期间,不修改源码对已有方法进行增强。
优势:
减少重复代码
提高开发效率
维护方便

AOP 的实现方式

AOP 的具体应用

使用自定义动态代理实现转账操作

pom.xml配置

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    </dependencies>

配置account

 private int id;
    private String name;
    private Float money;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

bean.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<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"
       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">

    <context:component-scan base-package="com.itheim"/>
    <bean id="proxyAccountService" factory-bean="proxyService" factory-method="getaccountService"/>

    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"/>
    <!-- 配置代理对象 -->
    <bean id="proxyService" class="com.itheim.proxy.proxyService">
        <property name="transactionManager" ref="transactionManager"/>
        <property name="service" ref="accountService"/>
    </bean>
    <bean id="transactionManager" class="com.itheim.Utils.TransactionManager">
        <property name="connectionUtils" ref="ConnectionUtils"/>
    </bean>
    <!-- 配置连接对象 -->
    <bean id="ConnectionUtils" class="com.itheim.Utils.ConnectionUtils">
        <property name="dataSource" ref="ds"/>
    </bean>
    <bean id="accountService" class="com.itheim.service.Imp.accountServiceImp"/>

    <!-- 配置数据源 -->
    <bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>

</beans>

配置业务逻辑层接口和实现类

public interface accountService {
    //业务层接口
    void transfer(String sourceName,String targetName,Float money);
}


public class accountServiceImp implements accountService {
    @Autowired
    private accountDao accountDao;
    public void transfer(String sourceName, String targetName, Float money) {
        Account account= accountDao.findByAccount(sourceName);
        Account account1 = accountDao.findByAccount(targetName);
        account.setMoney(account.getMoney()-money);
        //更新用户数据
        accountDao.updateMoney(account);
//        int i=1/0;
        account1.setMoney(account1.getMoney()+money);
        accountDao.updateMoney(account1);

    }
}

配置数据访问层接口和实现类

public interface accountDao {
    public void updateMoney(Account account);

    public Account findByAccount(String name);
}



@Repository("accountDao")
public class accountDaoImp implements accountDao {
    @Autowired
    private QueryRunner runner;
    @Autowired
    private ConnectionUtils connectionUtils;
    public void updateMoney(Account account){
        try {
            runner.update(connectionUtils.getThreadConnection(),"update account set money=? where name=?",account.getMoney(),account.getName());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findByAccount(String name) {
        try {
            return runner.query(connectionUtils.getThreadConnection(),"select * from account where name=? ",new BeanHandler<Account>(Account.class),name);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}

配置连接工具类

/**
 * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
 */

public class ConnectionUtils {
    private ThreadLocal<Connection> tl=new ThreadLocal<Connection>();
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getThreadConnection() {
        Connection conn = tl.get();
        try {
            if (conn==null){
                conn = dataSource.getConnection();
                tl.set(conn);

            }
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public void removeConnect(){
        tl.remove();
    }
}

配置控制事务的类

/**
 * 控制事务的类 开启事务 提交事务 回滚事务 关闭连接
 */
public class TransactionManager {
    private  ConnectionUtils connectionUtils;

    public  void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务
     */
    public  void beginTransaction() throws SQLException {
        connectionUtils.getThreadConnection().setAutoCommit(false);
    }

    /**
     * 提交事务
     */
    public void Commit(){
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 释放连接
     */
    public void close(){
        try {
            connectionUtils.getThreadConnection().close();
            connectionUtils.removeConnect();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

基于接口实现编写动态代理类

public class proxyService {

    private TransactionManager transactionManager;
    private accountService service;

    public void setService(accountService service) {
        this.service = service;
    }

    public final void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public accountService getaccountService() throws SQLException {
        return (accountService) Proxy.newProxyInstance(service.getClass().getClassLoader(),service.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object rtValue=null;
                try {
                    transactionManager.beginTransaction();
                    rtValue=method.invoke(service,args);
                    transactionManager.Commit();
                    return rtValue;
                } catch (Exception e) {
                    //当发生异常时回滚事务
                    transactionManager.rollback();
                    throw new RuntimeException(e);
                }finally {

                    //释放连接
                    transactionManager.close();

                }
            }
        });


    }
}

基于子类实现的动态代理

/**
* 基于子类的动态代理
* 要求:
* 被代理对象不能是最终类
* 用到的类:
* Enhancer
* 用到的方法:
* create(Class, Callback)
* 方法的参数:
* Class:被代理对象的字节码
* Callback:如何代理
* @param args
*/

public static void main(String[] args) {
final Actor actor = new Actor();
Actor cglibActor = (Actor) Enhancer.create(actor.getClass(),
new MethodInterceptor() {
/**
* 执行被代理对象的任何方法,都会经过该方法。在此方法内部就可以对被代理对象的任何
方法进行增强。
*
* 参数:
* 前三个和基于接口的动态代理是一样的。
* MethodProxy:当前执行方法的代理对象。
* 返回值:
* 当前执行方法的返回值
*/
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
String name = method.getName();
Float money = (Float) args[0];
Object rtValue = null;
if("basicAct".equals(name)){
//基本演出
if(money > 2000){
rtValue = method.invoke(actor, money/2);
}
}
if("dangerAct".equals(name)){
//危险演出
if(money > 5000){
rtValue = method.invoke(actor, money/2);
}
}
return rtValue;
}
});
cglibActor.basicAct(10000);
cglibActor.dangerAct(100000);
}
}

测试类

public class Client {
    public static void main(String[] args) throws SQLException {
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        accountService service = (accountService) ac.getBean("proxyAccountService");
        service.transfer("zhangsan","lisi",200f);
    }
}

AOP 相关术语

Joinpoint( 连接点):
所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的
连接点。
Pointcut( 切入点):
所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义。
Advice( 通知/ 增强):
所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
Introduction( 引介):
引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方
法或 Field。
Target( 目标对象):
代理的目标对象。
Weaving( 织入):
是指把增强应用到目标对象来创建新的代理对象的过程。
spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
Proxy (代理):
一个类被 AOP 织入增强后,就产生一个结果代理类。
Aspect( 切面):
是切入点和通知(引介)的结合。

学习 spring 中的 AOP 要明白的事

a 、开发阶段(我们做的)
编写核心业务代码(开发主线):大部分程序员来做,要求熟悉业务需求。
把公用代码抽取出来,制作成通知。(开发阶段最后再做):AOP 编程人员来做。
在配置文件中,声明切入点与通知间的关系,即切面。:AOP 编程人员来做。
b 、运行阶段(Spring 框架完成的)
Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对
象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。

使用Spring AOP 实现转账操作

导包

bean.xml 导入约束

xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
<!--配置事务管理器-->
    <bean id="transactionManager" class="com.itheim.Utils.TransactionManager">
        <property name="connectionUtils" ref="ConnectionUtils"/>
    </bean>
<!-- 配置aop -->
aop:config:
作用:用于声明开始 aop 的配置

<aop:config>
        

<!-- 
  
-->

        <aop:aspect id="txAdvice" ref="transactionManager">
            <aop:before method="beginTransaction" pointcut-ref="tl"/>
            <aop:after-returning method="Commit" pointcut-ref="tl"/>
            <aop:after-throwing method="rollback" pointcut-ref="tl"/>
            <aop:after method="close" pointcut-ref="tl"/>
        </aop:aspect>
</aop:config>

切入点表达式说明

execution:匹配方法的执行(常用)
execution(表达式)
表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))
写法说明:
全匹配方式:
public void
com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
访问修饰符可以省略
void
com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
返回值可以使用*号,表示任意返回值
*
com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
包名可以使用*号,表示任意包,但是有几级包,需要写几个*
* *.*.*.*.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
使用..来表示当前包,及其子包
* com..AccountServiceImpl.saveAccount(com.itheima.domain.Account)
类名可以使用*号,表示任意类
* com..*.saveAccount(com.itheima.domain.Account)
方法名可以使用*号,表示任意方法
* com..*.*( com.itheima.domain.Account)
参数列表可以使用*,表示参数可以是任意数据类型,但是必须有参数
* com..*.*(*)
参数列表可以使用..表示有无参数均可,有参数可以是任意类型
* com..*.*(..)
全通配方式:
* *..*.*(..)
注:
通常情况下,我们都是对业务层的方法进行增强,所以切入点表达式都是切到业务层实现类。
execution(* com.itheima.service.impl.*.*(..))

环绕通知

配置方式:
<aop:config>
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
<aop:aspect id="txAdvice" ref="txManager">
<!-- 配置环绕通知 -->
<aop:around method="transactionAround" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>
aop:around :
作用:
用于配置环绕通知
属性:
method:指定通知中方法的名称。
pointct:定义切入点表达式
pointcut-ref:指定切入点表达式的引用
说明:
它是 spring 框架为我们提供的一种可以在代码中手动控制增强代码什么时候执行的方式。
注意:
通常情况下,环绕通知都是独立使用的

pom.xml导入包

//解析bean.xml中的aop:pointcut表达式
<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
</dependency>

AOP 常用标签



aop:pointcut :
         作用:
              用于配置切入点表达式。就是指定对哪些类的哪些方法进行增强。
         属性:
               expression:用于定义切入点表达式。
                id:用于给切入点表达式提供一个唯一标识
        <aop:pointcut id="tl" expression="execution(* com.itheim.service.Imp.*.*(..))"/>

        aop:aspect:
        作用:用于配置切面。
         属性:
       id:给切面提供一个唯一标识。
       ref:引用配置好的通知类 bean 的 id。

aop:before
作用:
用于配置前置通知。指定增强的方法在切入点方法之前执行
属性:
method:用于指定通知类中的增强方法名称
ponitcut-ref:用于指定切入点的表达式的引用
poinitcut:用于指定切入点表达式
执行时间点:
切入点方法执行之前执行

aop:after-returning
作用:
用于配置后置通知
属性:
method :指定通知中方法的名称。
pointct :定义切入点表达式
pointcut-ref :指定切入点表达式的引用
执行时间点:
切入点方法正常执行之后。它和异常通知只能有一个执行

aop:after-throwing
作用:
用于配置异常通知
属性:
method :指定通知中方法的名称。
pointct :定义切入点表达式
pointcut-ref :指定切入点表达式的引用
执行时间点:
切入点方法执行产生异常后执行。它和后置通知只能执行一个

aop:after
作用:
用于配置最终通知
属性:
method :指定通知中方法的名称。
pointct :定义切入点表达式
pointcut-ref :指定切入点表达式的引用
执行时间点:
无论切入点方法执行时是否有异常,它都会在其后面执行。

基于注解的AOp配置

常用注解
@AsPect 标志该类是切面类
@Before() 标志这儿方法为前置方法
@AfterReturning() 标志该方法为后置方法
@AfterThrowing() 标志该方法为异常方法 异常时执行
@After() 标志该方法为最终方法 最终执行
@Pointcut() 用于指定切入点表达式
@Around() 用于指定环绕方法

//事务管理类配置
@Aspect
@Component("transactionManager")
public class TransactionManager {
    @Autowired
    private  ConnectionUtils connectionUtils;

    @Pointcut("execution(* com.itheim.service.Imp.*.*(..))")
    public void pt1(){

    }

    /**
     * 开启事务
     */
    @Before("pt1()") //注意加括号
    public  void beginTransaction() throws SQLException {
        connectionUtils.getThreadConnection().setAutoCommit(false);
    }

    /**
     * 提交事务
     */
    @AfterReturning("pt1()")
    public void Commit(){
        try {
            connectionUtils.getThreadConnection().commit();
            System.out.println("提交数据");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    @AfterThrowing("pt1()")
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 释放连接
     */
    @After("pt1()")
    public void close(){
        try {
            connectionUtils.getThreadConnection().close();
            System.out.println("关闭连接");
            //跟线程解绑
            connectionUtils.removeConnect();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

在 spring 配置文件中开启 spring 对注解 AOP 的支持

<!-- 开启 spring 对注解 AOP 的支持 -->
<aop:aspectj-autoproxy/>

环绕通知

/**
* 环绕通知
* @param pjp
* spring 框架为我们提供了一个接口:ProceedingJoinPoint,它可以作为环绕通知的方法参数。
* 在环绕通知执行时,spring 框架会为我们提供该接口的实现类对象,我们直接使用就行。
* @return
*/
public Object transactionAround(ProceedingJoinPoint pjp) {
//定义返回值
Object rtValue = null;
try {
//获取方法执行所需的参数
Object[] args = pjp.getArgs();
//前置通知:开启事务
beginTransaction();
//执行方法
rtValue = pjp.proceed(args);
//后置通知:提交事务
commit();
}catch(Throwable e) {
//异常通知:回滚事务
rollback();
e.printStackTrace();
}finally {
//最终通知:释放资源
release();
}
return rtValue;
}

不使用xml配置

@Configuration
@ComponentScan(basePackages="com.itheima")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}

猜你喜欢

转载自www.cnblogs.com/zgrey/p/13380352.html