java代码:
spring配置文件:
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
public class GenericLoggerBean {
private static Logger logger = LogManager.getLogger(GenericLoggerBean.class);
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println(joinPoint.getTarget().getClass());
logger.warn("Beginning method : " + joinPoint.getTarget().getClass() + "." + joinPoint.getSignature().getName()+ "()");
long startTime = System.currentTimeMillis();
try{
Object result = joinPoint.proceed();
return result;
}catch(Exception e){
logger.warn( joinPoint.getTarget().getClass() + "." + joinPoint.getSignature().getName() + "() invoke error" );
logger.warn("error info ["+e.getMessage()+"]");
}finally{
logger.warn("Ending method : " + joinPoint.getTarget().getClass() + "." + joinPoint.getSignature().getName() + "()");
logger.warn("Method invocation time : " + (System.currentTimeMillis() - startTime) + " ms.");
}
return null;
}
}
spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:config>
<aop:pointcut id="logger"
expression="execution( public * com.potato..*.*(..)) and !execution( * com.potato.core.aop.GenericLogger.*(..))" />
<aop:aspect id="loggerAspect" ref="genericLoggerBean">
<aop:around pointcut-ref="logger" method="invoke" />
</aop:aspect>
</aop:config>
<bean id="genericLoggerBean"
class="com.potato.core.aop.GenericLoggerBean">
</bean>
</beans>