Spring-AOP的使用

  • 引入 Spring 的基本jar包
  • 引入 aop 开发的相关jar包

  • 配置文件中引入 aop约束
<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
  • 主要的约束是以下内容
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd

关于测试

  • 测试时,每次都需要获取工厂
  • 通过 spring-test,就不用每次获取工厂了
  • 添加 spring-test 测试依赖包

  • 修改 applicationContext.xml
...

<bean id="goodsDao" class="top.it6666.dao.impl.GoodsDaoImpl"/>

...
  • 创建测试类代码如下:
/**
 * @author: BNTang
 **/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class GoodsDaoTest {

    @Resource(name = "goodsDao")
    private GoodsDao goodsDao;

    @Test
    public void Demo() {
        goodsDao.save();
    }
}
  • 编写一个 切面类
/**
 * @author: BNTang
 **/
public class MyAspect {
    public void checkPrivilege(){
        System.out.println("Permission to check");
    }
}
  • 将切面类交给 Spring
...

<bean id="goodsDao" class="top.it6666.dao.impl.GoodsDaoImpl"/>
<bean id="myAspect" class="top.it6666.aspect.MyAspect"/>

...
  • 配置 aop 完成对目标对象产生代理对象
  • 修改 applicationContext.xml
...

<bean id="goodsDao" class="top.it6666.dao.impl.GoodsDaoImpl"/>
<bean id="myAspect" class="top.it6666.aspect.MyAspect"/>

<aop:config>
    <aop:pointcut id="pointcut" expression="execution(* top.it6666.dao.impl.GoodsDaoImpl.save(..))"/>

    <aop:aspect ref="myAspect">
        <aop:before method="checkPrivilege" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>

...
  • 测试类代码还是上面的自行测试即可
posted @ 2020-10-14 23:18  BNTang  阅读(86)  评论(0编辑  收藏  举报