
熟练运用Spring(五):基于SpringAOP的日志记录实现
上一章节,我们对Spring AOP进行了快速入门,这一章节,我们会做一个简单的日志记录功能实现。
1 2 3 4 5 6 7 8 9 10 11 12
|
@Component public class Cook {
public void cooke(String name){ System.out.println(name + "制作中"); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
@Aspect @Component public class Log {
private String format = "yyyy-MM-dd HH:mm:ss";
public String createDate(Date date){ return new SimpleDateFormat(format).format(date); }
@Pointcut("execution(* spring05..*.*(String))" + "&& args(name)") private void method(String name){}
@Around("method(name)") private void around(ProceedingJoinPoint point,String name){ try { Signature sig = point.getSignature();//得到连接点的签名(这里相关被切方法的信息它都有) MethodSignature methodSignature = (MethodSignature) sig;//类型强制转换 Date start = new Date(); System.out.println(createDate(start) + ":开始调用 " + methodSignature.getMethod().toString() + " args(" + name + ")"); Object[] s = new Object[]{"1"}; point.proceed(s);//这里可将该被切方面的参数进行替换,具体根据业务场景在调整 System.out.println(createDate(new Date()) + ":结束调用 " + methodSignature.getMethod().toString() + " 总耗时:"+ (System.currentTimeMillis() - start.getTime())); } catch (Throwable throwable) { throwable.printStackTrace(); } } }
|
1 2 3 4 5
|
@Configuration @ComponentScan @EnableAspectJAutoProxy public class Spring05Config { }
|
1 2 3 4 5 6 7 8 9 10 11 12
|
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Spring05Config.class) public class Test03 {
@Autowired private Cook cook;
@Test public void test(){ cook.cooke("万"); } }
|
执行结果:
1 2 3
|
2018-12-09 18:20:12:开始调用 public void spring05.Cook.cooke(java.lang.String) args(万) 1制作中 2018-12-09 18:20:23:结束调用 public void spring05.Cook.cooke(java.lang.String) 总耗时:10021
|
近期评论