发布网友
共1个回答
热心网友
有配置的,代码示例如下:
这是业务测试类:
package aop.annotation.service;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service("deptSerivceImpl")
@Scope("prototype")
public class DeptSerivceImpl implements DeptService {
public DeptSerivceImpl(){}
public void delete() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("删除部门");
}
public void save() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("保存部门");
}
}
这个是切面测试类:
package aop.annotation.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
@Aspect
@Component("timeHander")
public class TimeHander {
@Pointcut("bean (*Service)")
public void myPointCut(){};
@Before("maPointCut()")
public void myBefore(){
System.out.println("-----执行前置处理-------");
}
@Around("myPointCut()")
public Object handerTime(ProceedingJoinPoint pjp){
try {
// 开始计时
StopWatch watch=new StopWatch(pjp.getTarget().getClass().getName());
watch.start(pjp.getSignature().getName());
Object obj=pjp.proceed();
// 停止计时
watch.stop();
System.out.println(watch.prettyPrint());
return obj;
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}//执行目标
}
}