带你了解Spring AOP的使用详解

目录
  • springmvc.xml
  • BankDao
  • AdminCheck
  • BankDaoImpl
  • LogInfo
  • Transmaction
  • AdminCheckInterceptor
  • LogInfoInceptor
  • TransmactionInterceptor
  • Test
  • 总结

springmvc.xml

<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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://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
    http://www.springframework.org/schema/tx
    https://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/mvc
    https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <bean id="adminCheck" class="cn.hp.impl.AdminCheck"></bean>
    <bean id="transmaction" class="cn.hp.impl.Transmaction"></bean>
    <bean id="bankDao" class="cn.hp.impl.BankDaoImpl">
<!--        <property name="adminCheck" ref="adminCheck"></property>-->
<!--        <property name="transmaction" ref="transmaction"></property>-->
    </bean>
<!--    <aop:config>-->
<!--&lt;!&ndash;        切入点,什么时候,执行什么切入进来&ndash;&gt;-->
<!--        <aop:pointcut id="savepoint" expression="execution(* cn.hp.impl.*.*(..))"/>-->
<!--&lt;!&ndash;        切面-用来做事情-执行业务逻辑之前-你要做或执行什么事情&ndash;&gt;-->
<!--        <aop:aspect id="adminincepter" ref="adminCheck">-->
<!--            <aop:before method="check" pointcut-ref="savepoint"></aop:before>-->
<!--        </aop:aspect>-->
<!--        -->
<!--        <aop:aspect id="transmactionincepter" ref="transmaction">-->
<!--            <aop:around method="dointcepter" pointcut-ref="savepoint"></aop:around>-->
<!--        </aop:aspect>-->
<!--    </aop:config>-->
    <bean id="logInfo" class="cn.hp.impl.LogInfo"></bean>
    <bean id="adminCheckInterceptor" class="cn.hp.interceptor.AdminCheckInterceptor">
        <property name="adminCheck" ref="adminCheck"></property>
    </bean>
    <bean id="logInfoInceptor" class="cn.hp.interceptor.LogInfoInceptor">
        <property name="logInfo" ref="logInfo"></property>
    </bean>
    <bean id="transmactionInterceptor" class="cn.hp.interceptor.TransmactionInterceptor">
        <property name="transmaction" ref="transmaction"></property>
    </bean>
<!--    注入代理类-->
    <bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean">
<!--代理对象是谁-->
        <property name="target" ref="bankDao"></property>
<!--        代理的接口-->
        <property name="proxyInterfaces" value="cn.hp.dao.BankDao"></property>
<!--        代理的通知组件-->
        <property name="interceptorNames">
            <list>
                <value>adminCheckInterceptor</value>
                <value>logInfoInceptor</value>
                <value>transmactionInterceptor</value>
            </list>
        </property>
    </bean>

</beans>

BankDao

package cn.hp.dao;
public interface BankDao {
    /**
     * 存钱
     */
    public void remit();
    /**
     * 取钱
     */
    public void withdrawMoney();
    /**
     * 转账
     */
    public void transferAccounts();
}

AdminCheck

package cn.hp.impl;
public class AdminCheck {
    public void check(){
        System.out.println("正在验证账号信息");
    }
}

BankDaoImpl

package cn.hp.impl;
import cn.hp.dao.BankDao;
public class BankDaoImpl implements BankDao {

    @Override
    public void remit() {
//        adminCheck.check();
//        transmaction.beginTransmaction();
        System.out.println("存钱的业务逻辑");
//        transmaction.closeTransmaction();
    }
    @Override
    public void withdrawMoney() {
//        adminCheck.check();
//        transmaction.beginTransmaction();
        System.out.println("取钱的业务逻辑");
//        transmaction.closeTransmaction();
    }
    @Override
    public void transferAccounts() {
        System.out.println("转账的业务逻辑");
    }
}

LogInfo

package cn.hp.impl;
public class LogInfo {
    public void write(){
        System.out.println("写日志中");
    }
}

Transmaction

package cn.hp.impl;
import org.aspectj.lang.ProceedingJoinPoint;
public class Transmaction {
    public void beginTransmaction(){
        System.out.println("开始事务");
    }
    public void closeTransmaction(){
        System.out.println("结束事务");
    }
    public void dointcepter(ProceedingJoinPoint point) throws Throwable {
        beginTransmaction();
        point.proceed();
        closeTransmaction();
    }
}

AdminCheckInterceptor

package cn.hp.interceptor;
import cn.hp.impl.AdminCheck;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
import java.util.Set;
public class AdminCheckInterceptor implements MethodBeforeAdvice {
    private AdminCheck adminCheck;
    public AdminCheck getAdminCheck() {
        return adminCheck;
    }
    public void setAdminCheck(AdminCheck adminCheck) {
        this.adminCheck = adminCheck;
    }
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        adminCheck.check();
    }
}

LogInfoInceptor

package cn.hp.interceptor;
import cn.hp.impl.LogInfo;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class LogInfoInceptor implements AfterReturningAdvice {
    private LogInfo logInfo;
    public LogInfo getLogInfo() {
        return logInfo;
    }
    public void setLogInfo(LogInfo logInfo) {
        this.logInfo = logInfo;
    }
    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        logInfo.write();
    }
}

TransmactionInterceptor

package cn.hp.interceptor;
import cn.hp.impl.Transmaction;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.ibatis.transaction.Transaction;
public class TransmactionInterceptor implements MethodInterceptor {
    private Transmaction transmaction;
    public Transmaction getTransmaction() {
        return transmaction;
    }
    public void setTransmaction(Transmaction transmaction) {
        this.transmaction = transmaction;
    }
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        transmaction.beginTransmaction();
        Object obj = invocation.proceed();
        transmaction.closeTransmaction();
        return obj;
    }
}

Test

package cn.hp.test;
import cn.hp.dao.BankDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
    public static void main(String[] args) {
        //test1();
//        test2();
        test3();
    }
    private static void test3() {
        ApplicationContext ac= new ClassPathXmlApplicationContext("springmvc.xml");
        BankDao proxyFactory = ac.getBean("proxyFactory", BankDao.class);
        proxyFactory.remit();
    }
    private static void test2() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
        BankDao bd = ac.getBean("bankDao",BankDao.class);
        bd.transferAccounts();
    }
    private static void test1() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
        BankDao bd = ac.getBean("bankDao",BankDao.class);
        bd.withdrawMoney();
    }
}

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注我们的更多内容!

(0)

相关推荐

  • SpringAop日志找不到方法的处理

    SpringAop日志找不到方法 错误截图: 显示没有找到该方法,于是我找到对应的类和对应的方法: 这里我用了反射来获取方法名和参数: 错误打印的结果显示方法名获取没有错误,于是我查看参数的类型是否有错 结果一个都对不上- int类型反射得到的class: Integer反射得到的Class: -终于知道之前错误里的Ljavexxxx是哪里来的了- 由于model是一个接口 model反射的Class得到的是他的子类org.springframework.validation.support.B

  • Aspectj与Spring AOP的对比分析

    1.简介 今天有多个可用的 AOP 库, 它们需要能够回答许多问题: 1.是否与用户现有的或新的应用程序兼容? 2.在哪里可以实现 AOP? 3.与自己的应用程序集成多快? 4.性能开销是多少? 在本文中, 我们将研究如何回答这些问题, 并介绍 Spring aop 和 AspectJ, 这是 Java 的两个最受欢迎的 aop 框架. 2.AOP概念 在开始之前, 让我们对术语和核心概念进行快速.高层次的审查: Aspect -- 一种标准代码/功能, 分散在应用程序中的多个位置, 通常与实际

  • 浅谈Spring AOP中args()和argNames的含义

    args()的作用主要有两点: 1.切入点表达式部分如果增加了args()部分,那么目标方法除了要满足execution部分,还要满足args()对方法参数的要求,对于符合execution表达式,但不符合args参数的方法,不会被植入切面. 2.定义了args()之后,才能把目标方法的参数传入到切面方法的参数中(通过Joinpoint也可以获取参数,但当前方法是直接用切面方法参数接受). 示例1 目标方法: @RestController @RequestMapping("/testAop&q

  • SpringAOP 如何通过JoinPoint获取参数名和值

    SpringAOP 通过JoinPoint获取参数名和值 在Java8之前,代码编译为class文件后,方法参数的类型固定,但是方法名称会丢失,方法名称会变成arg0.arg1-..在Java8开始可以在class文件中保留参数名. public void tet(JoinPoint joinPoint) { // 下面两个数组中,参数值和参数名的个数和位置是一一对应的. Object[] args = joinPoint.getArgs(); // 参数值 String[] argNames

  • SpringAOP切入点规范及获取方法参数的实现

    切入点规范 @Pointcut("execution(* com.example.server.service.TeacherService.*(..))") 上面的切入点会切入com.example.server.service.TeacherService下面的所有方法. 下面来详细介绍一下切入点表达式的规范. 1.execution():表达式主体. 2.第一个位置:表示返回类型, *号表示所有的类型. 3.第二个位置:表示需要拦截的包名.类名.方法名(方法参数). 需要注意的是

  • 带你了解Spring AOP的使用详解

    目录 springmvc.xml BankDao AdminCheck BankDaoImpl LogInfo Transmaction AdminCheckInterceptor LogInfoInceptor TransmactionInterceptor Test 总结 springmvc.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.

  • Spring AOP 基于注解详解及实例代码

    Spring AOP  基于注解详解及实例代码 1.启用spring对@AspectJ注解的支持: <beans xmlns:aop="http://www.springframework.org/schema/aop"...> <!--启动支持--> <aop:aspectj-autoproxy /> </beans> 也可以配置AnnotationAwareAspectJAutoProxyCreator Bean来启动Spring对@

  • Spring AOP  基于注解详解及实例代码

    Spring AOP  基于注解详解及实例代码 1.启用spring对@AspectJ注解的支持: <beans xmlns:aop="http://www.springframework.org/schema/aop"...> <!--启动支持--> <aop:aspectj-autoproxy /> </beans> 也可以配置AnnotationAwareAspectJAutoProxyCreator Bean来启动Spring对@

  • Spring AOP的使用详解

    什么是AOP AOP(Aspect Oriented Programming 面向切面编程),通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型.利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率. 常用于日志记录,性能统计,安全控制,事务处理,异常处理等等. 定义AOP术语 切面(Aspect):切

  • Spring 缓存抽象示例详解

    Spring缓存抽象概述 Spring框架自身并没有实现缓存解决方案,但是从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口,提供对缓存功能的声明,能够与多种流行的缓存实现集成. Cache接口为缓存的组件规范定义,包含缓存的各种操作集合: Cache接口下Spring提供了各种xxxCache的实现:如RedisCache,EhCacheCache , ConcurrentMapCa

  • spring结合hibernate示例详解

    单纯Hibernate程序 1.首先是导入hibernate的jar包. 2. 建立用户和用户操作记录实体,Log.Java和User.java.代码如下所示. Log.java import java.util.Date; public class Log { private int id; //日志的类别.日志一般起到一个不可否认性. //操作日志 安全日志 事件日志. private String type; private String detail; private Date time

  • 简单实现Spring的IOC原理详解

    控制反转(InversionofControl,缩写为IoC) 简单来说就是当自己需要一个对象的时候不需要自己手动去new一个,而是由其他容器来帮你提供:Spring里面就是IOC容器. 例如: 在Spring里面经常需要在Service这个装配一个Dao,一般是使用@Autowired注解:类似如下 public Class ServiceImpl{ @Autowired Dao dao; public void getData(){ dao.getData(); } 在这里未初始化Dao直接

  • Spring事务annotation原理详解

    这篇文章主要介绍了Spring事务annotation原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在使用Spring的时候,配置文件中我们经常看到 annotation-driven 这样的注解,其含义就是支持注解,一般根据前缀 tx.mvc 等也能很直白的理解出来分别的作用. <tx:annotation-driven/> 就是支持事务注解的(@Transactional) . <mvc:annotation-driven

  • Spring Cloud Ribbon配置详解

    本节我们主要介绍 Ribbon 的一些常用配置和配置 Ribbon 的两种方式. 常用配置 1. 禁用 Eureka 当我们在 RestTemplate 上添加 @LoadBalanced 注解后,就可以用服务名称来调用接口了,当有多个服务的时候,还能做负载均衡. 这是因为 Eureka 中的服务信息已经被拉取到了客户端本地,如果我们不想和 Eureka 集成,可以通过下面的配置方法将其禁用. # 禁用 Eureka ribbon.eureka.enabled=false 当我们禁用了 Eure

  • Spring事件监听详解

    一.观察者模式 先来看下观察者模式,举个例子 警察和军人是观察者,犯罪嫌疑人是被观察者 代码实现: 定义被观察者接口: 定义观察者接口 定义坏人 定义好人: 定义好人2: 测试: 或者用JDK自带的观察者模式 定义坏人: 定义好人: 测试: 结果: 最后来总结一下,看下spring的事件 二.spring事件 下面来看下源码 1 初始化事件广播器 可以看到如果没有自定义的事件广播器,默认是使用SimpleApplicationEventMulticaster的 三.注册监听器 其实就是把监听器添

随机推荐