AOP的原理和实例

AOP的原理
对哪些对象在什么位置拦截做什么 <=>
哪些对象
 
         
dataSourceAspect 是切面要拦截什么。aop:before就是在拦截对象的前面位置。method="before"就是使用切面中的方法处理拦截 
85  
86  
87
 
如上是用配置文件配置的
还有方法是直接用注解方式
注解中也说明了,拦截范围@Pointcut,在什么位置@Before,做什么@Aspect,具体拦截对象是谁JoinPoint
@Aspect
public class LoggingAspect {


// @Pointcut("execution(* com.samsung.sdsc.legal..*Impl.*(..)) || execution(* com.samsung.sdsc.legal..*Action.*(..))")
@Pointcut("execution(* com.samsung.sdsc.legal..*Impl.*(..))")
public void serviceMethod() {
}


@Before("serviceMethod()")
public void beforeLogging(JoinPoint thisJoinPoint) {
Class clazz = thisJoinPoint.getTarget().getClass();
Logger logger = Logger.getLogger(clazz);
String methodName = thisJoinPoint.getSignature().getName();
Object[] arguments = thisJoinPoint.getArgs();


StringBuffer argBuf = new StringBuffer();
StringBuffer argValueBuf = new StringBuffer();
int i = 0;
for (Object argument : arguments) {
String argClassName = "";
if (null == argument) {
argClassName = "Null";
argument = "";
} else {
argClassName = argument.getClass().getSimpleName();
}


if (i > 0) {
argBuf.append(", ");
}
argBuf.append(argClassName + " arg" + ++i);
argValueBuf.append(".arg" + i + " : " + argument.toString() + "\n");


}


if (i == 0) {
argValueBuf.append("No arguments\n");
}


StringBuffer messageBuf = new StringBuffer();
messageBuf.append("before executing " + methodName + "("
+ argBuf.toString() + ") method");
messageBuf
.append("\n-------------------------------------------------------------------------------\n");
messageBuf.append(argValueBuf.toString());
messageBuf
.append("-------------------------------------------------------------------------------");
logger.info(messageBuf);


}
}


请使用浏览器的分享功能分享到微信等