How can I use AOP to intercept the constructor of File, FileReader, FileWriter, FileInputStream and FileOutputStream?

删除回忆录丶 提交于 2019-12-01 04:41:48

Even though the answer linked to here by Sotirios Delimanolis is correct (I wrote it myself) insofar as AspectJ instead of proxy-based Spring AOP is necessary, please note that you cannot use execution(*.new(..)) for JDK classes because those are excluded from aspect weaving by default. In order to weave into JDK classes (execution joinpoints are logically in the callee code) you need to modify the JDK's rt.jar or at least put the modified JDK classes on the bootclasspath before the JDK itself. This is possible, but not so trivial.

But there is a simpler option: weave into the callers (your own code), not the callees via call(*.new(..)) - note the difference between call() and execution(). This in turn means that you cannot intercept calls to JDK classes not made from your own woven code or from the JDK itself. So if you need a 100% solution even for code not under your own control, you will end up weaving the JDK. Probably this is not necessary though if you just want to secure your own classes. :-)

As much as I am a huge fan of AspectJ, I want to highlight that I am also a firm proponent of clean code and refactoring. Any decent IDE like IntelliJ IDEA or Eclipse should make it quite simple to refactor 960 calls to use a safe wrapper class like you suggested. Why do you not do this if it is so important? IDEA's structural search and replace does that for you in minutes, if not seconds. AOP can, but should not be used to patch up your own code's deficiencies. So please go refactor, you will be much happier afterwards.

Sotirios Delimanolis

Simple Spring AOP (with proxying) does not support constructor join points.

Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans).

If you can go with aspectj, that should do the trick. Otherwise, you'll have to play with bytecode yourself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!