首先修改LogAspect.java,这里可以移除掉所有AOP相关的注解,只保留@Component。
接下来只要在beans.xml中配置切面,将这个类里的方法'切入'到要做log的类的方法就可以了。
package com.lj.proxy;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;
import com.lj.log.Logger;
/**
*这里只剩下@Component了,其它的注释都去掉了,都会通过beans.xml的信息让Spring自己来进行处理。
*/
@Component("logAspect")
public class LogAspect {
public void logStart(JoinPoint jp) {
// 返回类对象
System.out.println(jp.getTarget());
// Signature.getName()返回方法名称
System.out.println(jp.getSignature().getName());
Logger.info("加入日志");
}
public void endStart(JoinPoint jp) {
Logger.info("方法调用结束");
}
public void logAround(ProceedingJoinPoint proceedingJoinPoint) {
Logger.info("开始在Around中加入日志");
try {
proceedingJoinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 执行程序
Logger.info("Around执行结束");
}
}
接下来只要在beans.xml中配置切面,将这个类里的方法'切入'到要做log的类的方法就可以了。
<aop:config> <!-- ref对应的是@Component("logAspect") -->
<!-- 切面对象名称是logAspect -->
<aop:aspect id="logAspect" ref="logAspect">
<!-- 设置pointcut -->
<aop:pointcut id="logPointCut" expression="execution(* com.lj.dao.*.add*(..))||
execution(* com.lj.dao.*.loadBy*(..))" />
<!-- 设置@before的方法,pointcut-ref对应上面的pointcut id -->
<aop:before method="logStart" pointcut-ref="logPointCut"/>
<aop:after method="endStart" pointcut-ref="logPointCut"/>
<aop:around method="logAround" pointcut-ref="logPointCut"/>
<!-- method名称要对应LogAspect里面的方法名称 -->
</aop:aspect>
</aop:config>