I'm writing a method that tries to log db calls, form connecting to it, to after the query, there are many places that calls the method connect() to start and the cleanUp() method to end, I can't and don't want to modify every place. So the sequence is like this :
Connection con = ...
connect();
s = con.createStatement();
ResultSet rs = s.executeQuery(" select * from xyz ");
rs.next();
cleanUp();
There are many methods that uses this sequence, so how do I, somehow in cleanUp(), get the sql query string [ in this case : select * from xyz ] from all the methods that run their queries, is there a way to get that info from the "con", does the con object know what query it has just ran ?
解决方案
I suggest to you to use an aspect, AspectJ would be perfect for this case.
With an aspect, you could trigger a behavior once your monitored method has been executed.
Here are a couple examples you could check: http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html and https://mathewjhall.wordpress.com/2011/03/31/tracing-java-method-execution-with-aspectj/