本文主要是介绍AOP系列(二)——为符合条件的目标对象创建代理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
接着上篇文章,我们将采用新的方式进行动态代理。
ObjectNameAutoProxyCreator创建代理
实现思路
根据配置文件中的配置,Spring容器会根据此配置,为符合条件的对象创建代理。
具体代码
配置文件
<?xml version="1.0"?>
<configuration><configSections><sectionGroup name="spring"><section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/><section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/></sectionGroup></configSections><spring><context><resource uri="config://spring/objects"/></context><objects xmlns="http://www.springframework.net"><object id="beforeAdvice" type="AOPExample.LogBeforeAdvice,AOPExample"/><!--在容器中配置,必须的,以便在容器中可以根据后缀名Service查找到这个对象--><object id="userService" type="AOPExample.UserService,AOPExample"/><!--通过ObjectNameAutoProxyCreator自动创建AOP代理--> <object id="IServiceProxy" type="Spring.Aop.Framework.AutoProxy.ObjectNameAutoProxyCreator, Spring.Aop"><property name="ObjectNames"><list><!--只要是对象的后缀名为Service的,就会自动为它们创建代理--><value>*Service</value></list></property><property name="InterceptorNames"><list><value>beforeAdvice</value></list></property></object></objects></spring>
</configuration>
客户端
class Program{static void Main(string[] args){User enUser = new User() { Name ="Danny",Age=15};IApplicationContext context = ContextRegistry.GetContext();IUserService userService = (IUserService)context.GetObject("userService");userService.GetUserInfo(enUser);}}
总结
- 优点:在这个例子中Spring容器会为以名称Service结尾的多个目标对象生成代理类。
- 优点:在配置文件中只需要配置一次,而不用为每个目标对象都配置一次。
- 优点:客户端的代码不用更改,调用的还是接口,而不是代理类。
这篇关于AOP系列(二)——为符合条件的目标对象创建代理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!