Spring的AOP的开发:


针对所有方法的增强 :( 不带有切点的切面 )
第一步:导入相应jar包.
* spring-aop-3.2.0.RELEASE.jar
* com.springsource.org.aopalliance-1.0.0.jar
 
第二步:编写被代理对象:
* CustomerDao接口
* CustoemrDaoImpl实现类
 
第三步:编写增强的代码:
public class MyBeforeAdvice implements MethodBeforeAdvice{
 
/**
 * method:执行的方法
 * args:参数
 * target:目标对象
 */
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("前置增强...");
}
}
 
第四步:生成代理:(配置生成代理:)
* 生成代理Spring基于ProxyFactoryBean类.底层自动选择使用JDK的动态代理还是CGLIB的代理.
* 属性:
target : 代理的目标对象
proxyInterfaces : 代理要实现的接口
如果多个接口可以使用以下格式赋值
<list>
    <value></value>
    ....
</list>
proxyTargetClass : 是否对类代理而不是接口,设置为true时,使用CGLib代理
interceptorNames : 需要织入目标的Advice
singleton : 返回代理是否为单实例,默认为单例
optimize : 当设置为true时,强制使用CGLib
 
<!-- 定义目标对象 -->
<bean id="customerDao" class="cn.itcast.spring3.demo3.CustomerDaoImpl"></bean>
<!-- 定义增强 -->
<bean id="beforeAdvice" class="cn.itcast.spring3.demo3.MyBeforeAdvice"></bean>
 
<!-- Spring支持配置生成代理: -->
<bean id="customerDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 设置目标对象 -->
<property name="target" ref="customerDao"/>
<!-- 设置实现的接口 ,value中写接口的全路径 -->
<property name= "proxyInterfaces " value ="cn.itcast.spring3.demo3.CustomerDao"/>
<!-- 需要使用value:要的名称 -->
<property name="interceptorNames" value= "beforeAdvice"/>
</bean>
 
***** 注入的时候要注入代理对象:
@Autowired
// @Qualifier("customerDao")// 注入是真实的对象,必须注入代理对象.
@Qualifier(" customerDaoProxy ")
private CustomerDao customerDao;

猜你喜欢

转载自blog.csdn.net/qq_40036979/article/details/80214978