关于Java AOP和dotnet attribute, 有的人说, AOP是概念, attribute是技术, 不能混为一谈, 不过如果你想在不影响原有class hiberarchy的条件下, 用横切的方法去影响class或method的行为, 当你对.net程序员提这个要求, 他们想到的是attribute, 如果你对java程序员说, 他们肯定会说AOP, 所以无论是概念还是技术, 只要他们干的是有相同之处, 我们就不用去太在乎他的名字. 只专著他们的功能好了.
首先, AOP和dotnet Attribute都属于declarative programming(DP), DP的主要目的就是解决code reuse问题, 在不改code和少改code的情况下, 通过替换adapter来更改系统的功能。思路很象(object oriented programming)OOP里的options或style, 不同的是在OOP里, 你得把aa.options = .. 或setstyle(aa, ..)放到code里, 这样比较灵活, 但是一但功能变动, programer必须查看整个程序去找到对应的代码, 而且可能不只一处, 提高了系统的维护成本
就我目前所知, AOP多数是用xml来配置管理adapter, 这样不用更改code, 只要更改xml就可以了, 这确实比较方便, 但也带来了管理的问题, 比如, 我们用以下的code来配置和初始化adapter环境
--抄自nuke的spring framework open document, thanks
ApplicationContext ctx=new
FileSystemXmlApplicationContext("bean.xml");
Action action = (Action) ctx.getBean("TheAction");
很多时侯, 我们把这段初始化adapter的code封装到framework里base class的construction里,原因就不用說了。但这样一來, 当我们在开发系统时使用很多基于aop的framework时, 系统就得带有很多xml, 其它人是无法光从系统code知道系统到底执行了啥东西, 他们得从framework的文档或code里找到哪个xml被用到, 再去xml里看哪个element是针对哪个adapter的, 这样也提高了系统的维护成本。有的IDE支持可以缓解一些问题,比如在jbuilder, eclipse里加入spring 的配制插件去帮助修改xml。
dotnet attribute引入了attribute target的概念, target对应的是code的基本元素, 象method, class, 以及assembly(app), 比如
[webmethod]
procedure aaa(..);
这样做的好处简单的说, 一是缩小了adapter的在code里搜索范围, programer只要查看target就可以了, 二是adapter配制是在code里, programer也不用到处去找对应的xml和element,
缺点是当修改attribute 后必须re-compile, 不如AOP方便, 但也避免了AOP的reflection带来的cost, programmer 还可通过compiling error去找到Typo问题。
目前, java 5里也出现了类似的语法, 比如以下例子是EJB3里用来实现Dependency Injection, 很象以前java xdoclet里的annotations .
@EJB(name="calculator", jndiName = "org.jboss.tutorial.injection.bean.Calculator")
public void setCalculator(Calculator c)
{
set = c;
}