
代理的实现{有接口+实现类:spring采用jdk动态代理Proxy只有实现类:spring采用cgliv字节码增强在.xml的代理工厂配置上有optmize配置
\mathrm{代理的实现}\left\{\begin{array}{l}\mathrm{有接口+实现类:}spring采用jdk动态代理Proxy\\\mathrm{只有实现类:}spring采用cgliv字节码增强\\\end{array}\right.\\
在.xml的代理工厂配置上有optmize配置
代理的实现{有接口+实现类:spring采用jdk动态代理Proxy只有实现类:spring采用cgliv字节码增强在.xml的代理工厂配置上有optmize配置
<property name="optmize" value="true/false"></property>
<!--一般如果目标类有接口,采用jdk动态代理,没有接口,采用cglib字节码增强,如果选择true,则全部使用cglib-->
手动实现jdk动态代理要编写的要素:
{目标类:接口+实现类切面类:存放通知工厂类:编写工厂生成代理测试类 \left\{\begin{array}{l}\mathrm{目标类}:\mathrm{接口}+\mathrm{实现类}\\\mathrm{切面类}:\mathrm{存放通知}\\\mathrm{工厂类}:\mathrm{编写工厂生成代理}\\\mathrm{测试类}\end{array}\right. ⎩⎪⎪⎨⎪⎪⎧目标类:接口+实现类切面类:存放通知工厂类:编写工厂生成代理测试类
Spring编写半自动代理:
导入.jar包{4+1AOP联盟Spring(实现)−aop \mathrm{导入}.jar包\left\{\begin{array}{l}4+1\\AOP\mathrm{联盟}\\Spring(\mathrm{实现})-aop\end{array}\right. 导入.jar包⎩⎨⎧4+1AOP联盟Spring(实现)−aop
AOP联盟将通知/增强分为5类,这里主要应用环绕通知MethodInterceptor(intercept截取拦截)
try{
//前置通知
//执行目标方法
//后置通知
}catch(){
//异常通知
}
目标类的接口与实现类的写法不变
原来的切面类中确定通知,现在删掉before,after写上invoke
pulic class MyAspect implements MethodInterceptor{
public Object invoke(MethodInvocation mi )throws Throable{
System.out.println("前");
Object obj=mi.procede();//手动执行目标方法
System.out.println("后");
return obj;
}
}
测试:(注意:.getBean(“代理类的id”)😉
public void demo(){
String xmlpath ="com.···.beans.xml"
ApplicationContext applicationContext= new ClassPathXmlApplicationContext(xmlpath);
UserSersvice userSvice =(UserSvice)applicationContext.getBean("代理类的id");
userSvice .adduser();
userSvice .updateuser();
userSvice .deleteuser();
}
.xml配置
<?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="UserId" class="com.~.UserServiceImpl"></bean>
<!-- 切面类 -->
<bean id="MyAspectId" class="com.~.MyAspect"></bean>
<!-- 设置代理工厂 -->
<bean id="proxuServiceId" class="org.springframework.aop.framework.ProxyFactoryBean(用于生产代理对像的类)">
<!-- 代理接口-->
<property name="Interface" value="全限定.UserService"></property>
如果多个接口:
<property name="Interfaces" ><array><value>全限定.UserService</value></array></property>
<!-- 目标类 -->
<property name="target" ref="UserServiceId"></property>
<!-- 切面类 -->
<property name="interceptorNames" value="MyAspectId(多个值仍使用子标签)"></property>
</bean>
</beans>
全自动Spring Aop 编程
1.导入com.springsource.org.aspectj.weaver.RELEASE.jar
2.在.xml中的配置中,目标类,切面类不变,Test中getBean(目标类Id)
3.下面更改xml文件实现Spring aop编程
使用aop:config进行配置
<!--aop标签支持-->
<aop:config>
<!--切入点表达式-->
<aop:pointcut id="mypointcut" expression="execution( * com.~.UserServiceImpl.*(..))"/>
<!--组合通知与切入点-->
<aop:advisor advice-ref="MyAspectId" pointcut-ref="mypointcut"/>
</aop:config>

Spring AOP 实现解析
本文介绍了Spring AOP(面向切面编程)的实现方式,包括动态代理与字节码增强技术的选择,并详细展示了如何手动实现JDK动态代理及Spring框架下的AOP编程。
394

被折叠的 条评论
为什么被折叠?



