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