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();

    }
}

猜你喜欢

转载自www.cnblogs.com/shouyaya/p/12549649.html
今日推荐