我正在使用Spring 3.0框架,并且还是一个新手。有人能用通俗易懂的语言解释一下什么是AOP编程吗?(一个简短的例子肯定会有帮助)
Spring如何结合/增强/支持它?
我正在使用Spring 3.0框架,并且还是一个新手。有人能用通俗易懂的语言解释一下什么是AOP编程吗?(一个简短的例子肯定会有帮助)
Spring如何结合/增强/支持它?
AOP是一种在代码库中修改现有类以根据单独定义的规则进行装饰或更改其行为的方式。这种修改可以在将类放入jar / war之前完成,也可以在加载代码时动态进行。
这个想法是,而不是在源代码中找到要修改的所有代码点并手动修改它们,您可以为如何查找代码库中感兴趣的点以及要执行的装饰定义规则。这些规则被称为方面(AOP的A)。
原型示例是,您想要获取代码库中各种方法的一些计时信息。您可以找到所有感兴趣的方法,并在顶部调用一个方法。
long start = System.currentTimeMillis();
最后执行以下操作:
long end = System.currentTimeMillis();
System.out.println("Method time is: " + (end - start));
但这可能需要大量的工作,而且它是暂时性的,您不希望破坏您的代码库。
当应用AOP时,无论是在创建jar文件时还是在类加载时,都好像您最初就是以这种方式编写这些类一样。
AOP是一种用于模块化横切功能的模式。因此,如果有某个“事物”适用于您代码中的大部分,则可以使用AOP来解决该问题。这些“事物”称为方面。
以下是一个示例:
企业应用程序中使用异常记录器。因此,您可以使用以下方式设置它。现在,my.service包下的所有方法都将以以下方式记录日志。
<bean id="exceptionLogger" class="my.good.ExceptionLogger" />
<aop:config>
<aop:pointcut id="allServiceMethods" expression="execution(* my.service.*(..))" />
<aop:aspect id="serviceLogger" ref="exceptionLogger">
<aop:after-throwing pointcut-ref="allServiceMethods"
method="logIt"
throwing="e"/>
</aop:aspect>
</aop:config>
public class ExceptionLogger {
private static Logger logger = Logger.getLogger(ExceptionLogger.class);
public void logIt(JoinPoint jp, Exception e) {
StringBuilder msg = new StringBuilder();
msg.append("<whatever makes sense>");
logger.error(msg.toString());
}
}
同时也可以查看相关问题:
面向切面编程是一种相对较新的编程方式,它并不是面向对象编程的替代品。事实上,AOP是另一种组织程序结构的方式。
为了更加清晰,我将使用一些图表:
What is Aspect?
|---------------------|------------------|------------------|
| Aspect = Point cut + Advice |
|---------------------|------------------|------------------|
| | Where the aspect | What code is |
| | is applied | executed. |
|---------------------|------------------|------------------|
Aspect = Point cut + Advice
Type of Advice methods
Aspect Example
@Around( "execution(* *(..))" )
public Object trace(ProceedingJoinPointproceedingJP)throwsThrowable{
String methodInformation= proceedingJP.getStaticPart().getSignature().toString();
logger.trace("Entering "+methodInformation);
try{
returnproceedingJP.proceed();
} catch(Throwable ex) {
logger.error("Exception in "+methodInformation, ex);
throw ex;
} finally {
logger.trace("Exiting "+methodInformation);
}
}