Spring中AOP开发步骤

AOP:不是由Spring定义.AOP联盟的组织定义.

Spring中的通知:(增强代码)

前置通知 org.springframework.aop.MethodBeforeAdvice

* 在目标方法执行前实施增强

后置通知 org.springframework.aop.AfterReturningAdvice

* 在目标方法执行后实施增强

环绕通知 org.aopalliance.intercept.MethodInterceptor

* 在目标方法执行前后实施增强

异常抛出通知 org.springframework.aop.ThrowsAdvice

* 在方法抛出异常后实施增强

第一步:导入相应jar包.

* spring-aop-3.2.0.RELEASE.jar
* com.springsource.org.aopalliance-1.0.0.jar

第二步:编写被代理对象:

* CustomerDao接口
* CustoemrDaoImpl实现类

第三步:写一个类继承相关Advice的接口:

public class MyBeforeAdvice implements MethodBeforeAdvice{

        /**
         * method:执行的方法
         * args:参数
         * target:目标对象
         */
    public void before(Method method, Object[] args, Object target)throws Throwable {
        System.out.println("前置增强...");
    }
}

 

第四步:生成代理:(配置生成代理:)

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="customerDao" class="cn.itcast.aop.dao.CustomerDaoImpl"/>


<!-- 定义增强对象 -->
<bean id="beforeAdvice" class="cn.itcast.aop.advice.MyBeforeAdvice"/>
<!-- 使用spring框架生成代理对象 -->
<bean id="customerDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 代理的目标对象 -->
<property name="target" ref="customerDao"></property>
<!-- 设置实现的接口告诉代理实现的接口跟CustomerDaoImpl实现类实现的接口一样 -->
<property name="proxyInterfaces" value="cn.itcast.aop.dao.CustomerDao"></property>
<!-- 增强是通知name="interceptorNames"拦截所有的方法    value="beforeAdvice" 增强的通知告诉代理对象应该使用前置增强-->
<property name="interceptorNames" value="beforeAdvice"></property>
</bean>

</beans>

第五步:编写测试类

利用spring集成junit将我们需要的目标类注入到测试类中

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
    @Autowired
    // @Qualifier("customerDao")//注入真实对象
    @Qualifier("customerDaoProxy")//注入代理对象
    private CustomerDao customerDao;

    @Test
    public void test(){
        customerDao.add();
        customerDao.delete();
        customerDao.find();
        customerDao.update();
    }
}

 

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值