• Spring Aop(面向切面编程)


     

    相关术语:

     

     spring底层生成代理有两种模式:JDK动态代理(对象必须实现了接口)和CGLIB生成代理(对象可不需实现接口)

     

     

     

     

     

     1.maven引入两个依赖:

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>aopalliance</groupId>
          <artifactId>aopalliance</artifactId>
          <version>1.0</version>
        </dependency>

    2.配置applicationContext.xml的Spring配置文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!--配置目标类-->
        <bean id="studentDao" class="com.imooc.aop.demo6.StudentDaoImpl"/>
        <bean id="customerDao" class="com.imooc.aop.demo6.CustomerDao"/>
    
        <!-- 配置增强-->
        <bean id="myBeforeAdvice" class="com.imooc.aop.demo6.MyBeforeAdvice"/>
        <bean id="myAroundAdvice" class="com.imooc.aop.demo6.MyAroundAdvice"/>
    
        <!--配置切面-->
        <bean id="myAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
            <property name="pattern" value="com.imooc.aop.demo6.CustomerDao.save"/>   <!--配置匹配的对象中的方法,.需用转义字符标记-->
            <property name="advice" ref="myAroundAdvice"/>      <!--配置增强的方法-->
        </bean>
    
        <!-- 让目标对象实体化时自动生成其对应的代理对象,并代替 -->
        <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
    </beans>

    3.实例使用:

    package com.imooc.aop.demo6;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import javax.annotation.Resource;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext4.xml")
    public class SpringDemo6 {
        @Resource(name="studentDao")
        private StudentDao studentDao;
        @Resource(name="customerDao")
        private CustomerDao customerDao;
    
        @Test
        public void demo1(){
            studentDao.find();
            studentDao.save();
            studentDao.update();
            studentDao.delete();
    
            customerDao.find();
            customerDao.save();
            customerDao.update();
            customerDao.delete();
    
        }
    }
  • 相关阅读:
    【并查集】亲戚
    【图论】Car的旅行线路 NOIP 2001
    【贪心】排座椅
    【DP】花店橱窗布置
    【NOIP】NOIP考纲总结+NOIP考前经验谈
    【NOIP】考前须知
    NOIP 2016 PJ T4 魔法阵
    NOIP 2016 PJ T3 海港
    【高精度】麦森数 NOIP 2003
    【带权并查集】食物链 NOIP 2001
  • 原文地址:https://www.cnblogs.com/shouyaya/p/12549649.html
Copyright © 2020-2023  润新知