Spring Aop实现自定义拦截器

Spring体系和Aop就不多说了,反正我也一知半解。因项目需求搭建基于Spring的框架,在考虑异常处理和权限校验的时候使用Spring的Aop进行实现。

关于Spring Aop的介绍如果需要了解推荐文章:彻底征服Spring Aop

因为不是web项目,所以springmvc提供的一些已经实现好的东西就没法直接用,只能使用aop自己去实现。当然也许本身有实现好了的我没发现而已。

研究了一下,记录下实现过程,以便之后再用直接cp过来。
使用注解方式,话不多说,具体实现如下。

1. 新建拦截器

这里是自定义的核心模块,即拦截器的逻辑实现部分。

//让spring扫描这个bean
@Component("authInterceptor")
//声明为切面,这样才能成为拦截器
@Aspect
public class AuthCheckInteceptor {

    private final Logger logger = LoggerFactory.getLogger(AuthCheckInteceptor.class);
    //声明切面规则,即什么类的什么方法会被joinpoint,即哪里会被拦截
    @Pointcut("execution(* com.cup.ares.bdsp.magpie.rpc.impl.*.*(..))")
    private void doIntercept() {

    }
    //在方法执行前拦截
    @Before(value = "doIntercept()")
    public void before(JoinPoint point) {
        logger.info("BBBBBBBBBBBBBBBBBBBBBBBBefore method invoke,{}");
    }
    
    //在方法执行中拦截
    /*注意此处的args(queryStr)是因为这里的around方法声明里增加了参数 String queryStr,这表示在符合上面的Pointcut规则的方法中,只有含有且仅含有一个参数为queryStr的方法才会被拦截。
    此外,此处可以定义返回值,如果为void则对原方法不会有影响,如果声明了返回值,此处如果修改,将最终返回给业务方法的调用者。
    */
    @Around(value = "doIntercept() and args(queryStr)")
    public Object around(ProceedingJoinPoint joinpont, String queryStr) {
        //实验发现这里的代码上面声明的before先执行
        logger.info("ARRRRRRRRRRRRRRRRRRRRRRRRRRRound,{}", queryStr);
        try {
            //执行业务方法
            String r = (String)joinpont.proceed();
            //执行之后,可以对返回值任意操作
            r=r+"xxxxxxxxxxxxxxxx";
            return r;
        } catch (Throwable e) {
            //异常处理,可以借助这个逻辑实现异常拦截器
            r="exception"+e.getMessage();
            logger.info("EEEEEEEEEEEEEEEEEEEEEEEEEEE", e);
            return res;
        }
    }
    
    //方法执行后
    @After("doIntercept()")
    public void after() {
        logger.info("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfter method invoke");
    }
    //异常处理完成之后
    @AfterThrowing(value = "doIntercept()  &&  args(ex)")
    public void afterT(Throwable ex) {
        logger.error("CCCCCCCCCCCCCCCCCCCCCCatch Exception", ex);
    }

}

2. 配置文件修改

使用注解给我们带来很多方便,不用再去配置。不过在spring的配置文件中还是要加上一些。

//自动扫描我们定义的拦截器,当然如果只有一个拦截器类,也可以使用普通的bean标签来定义这个拦截器
<context:component-scan base-package="com.cup.ares.bdsp.interceptor" />
//开启切面注解,这样才能使@Aspect生效
<aop:aspectj-autoproxy />

3. 被拦截的类

@Service("billDataService")
public class BillDataServiceImpl implements BillDataService {
    private final Logger logger = LoggerFactory.getLogger(BillDataServiceImpl.class);

    @Override
    public String simpleQueryBySingle(String queryStr) {
        logger.info("卡号:{}命中黄牛名单!", data.getBillValue());
        return "invoke res";
    }

}

可以看到被拦截的类无需任何修改,完全无感知无侵入。

附上pom清单和spring配置,可能有些不是必要的,自己删除。

        <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <org.springframework.groupid>org.springframework</org.springframework.groupid>
        <org.springframework.version>4.3.5.RELEASE</org.springframework.version>
        <org.hibernate.groupid>org.hibernate</org.hibernate.groupid>
        <org.hibernate.version>4.3.9.Final</org.hibernate.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>com.cup.ares</groupId>
                <artifactId>bdsp_svc_magpie</artifactId>
                <version>0.0.1-SNAPSHOT</version>
            </dependency>
            <!-- spring -->
            <dependency>
                <groupId>${org.springframework.groupid}</groupId>
                <artifactId>spring-context</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>${org.springframework.groupid}</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>${org.springframework.groupid}</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
            <dependency>
                <groupId>${org.springframework.groupid}</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${org.springframework.version}</version>
            </dependency>
        </dependencies>

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:magpie="http://www.unionpay.com/schema/magpie"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                   http://www.unionpay.com/schema/magpie http://www.unionpay.com/schema/magpie/magpie.xsd
                   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                   http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
    default-lazy-init="false">
        <!-- bean自动扫描 -->
        <context:component-scan base-package="com.cup.ares.bdsp.service.impl" />
        <context:component-scan base-package="com.cup.ares.bdsp.interceptor" />
        <!-- 扫描properties配置 -->
        <bean id="propertyPlaceholderConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath:server.properties</value>
                </list>
            </property>
        </bean>
        <!-- datasource -->
        <bean id="dataSource" destroy-method="close"
            class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver" />
            <property name="jdbcUrl" value="${DB_Url}" />
            <property name="user" value="${DB_UserName}" />
            <property name="password" value="${DB_Pwd}" />
            <property name="initialPoolSize" value="${DB_InitialPoolSize}" />
            <property name="minPoolSize" value="${DB_MinPoolSize}" />
            <property name="maxPoolSize" value="${DB_MaxPoolSize}" />
            <property name="maxIdleTime" value="${DB_MaxIdleTime_Sec}" />
        </bean>
    
        <bean id="sessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hibernate.hbm2ddl.auto">update</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.format_sql">true</prop>
                </props>
            </property>
            <property name="packagesToScan">
                <list>
                    <!-- 注意这里写到包名就行,不要写成 xx.xx.* -->
                    <value>com.cup.ares.bdsp.entity</value>
                </list>
            </property>
        </bean>
        <!-- 配置Spring声明式事务 -->
        <bean id="transactionManager"
            class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        <!-- 声明式事务实现1:注解方式 <tx:annotation-driven transaction-manager="transactionManager" 
            /> -->
        <!-- 声明式事务实现2:配置方式 start -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="get*" read-only="true" />
                <tx:method name="add*" propagation="REQUIRED" />
                <tx:method name="save*" propagation="REQUIRED" />
                <tx:method name="set*" propagation="REQUIRED" />
                <tx:method name="*" />
            </tx:attributes>
        </tx:advice>
        <!-- 配置事务切点,并把切点和事务属性关联起来 -->
        <aop:config>
            <aop:pointcut expression="execution(* com.cup.ares.bdsp.service.impl.*.*(..))"
                id="txPointcut" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
        </aop:config>
        <!-- 声明式事务实现2:配置方式 end -->
         <aop:aspectj-autoproxy />
    </beans>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,566评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,714评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,279评论 25 707
  • 慢跑有一个非常久远的历史,可对于我而言,它才刚刚开始。 我就是这样怀抱着一份莫名的寄托感开始了我人生之中又一次的慢...
    西可森林阅读 312评论 0 0
  • 抄袭应该是个敏感词,一般不拿到台面上说。但我说了抄袭并不是改个名字,直接照搬,而是对优秀作品进行学习,吸取优秀的适...
    朗里格朗朗阅读 603评论 0 0