强制代码片段始终出现在一组 Java 类中
我必须确保在某个包下的类的所有公共方法中执行代码片段:
public String doStuff(String a, Integer b, Context c) {
current.put(c); <--- code that need to be executed
// business logic
...
}
确保该代码片段始终出现在作为第一行的最佳方法是什么每个公共方法?
我考虑过使用一些静态代码分析工具,例如PMD。另外,我相信编译时 AOP 会有所帮助。还有什么想法,指点一下?
我知道我可以使用一个方面来实现这一点。问题是我的应用程序正在使用 Spring,但我需要“检查”的类不是 spring 管理的 - 另外,我想避免更改服务器启动选项以启用基于 Spring 注释的运行时编织。
编辑: 我必须强制执行代码的类是 Akka 类型的 Actor。
I have to be sure that a snippet of code get executed in all public methods of classes under a certain package:
public String doStuff(String a, Integer b, Context c) {
current.put(c); <--- code that need to be executed
// business logic
...
}
What would be the best approach for ensuring that that snippet of code is always present AS THE FIRST LINE of each public method?
I have considered using some static code analysis tool, such as PMD. Also, I believe compile time AOP could help. Any more idea, pointers?
I know that I can use an Aspect for that. Problem is that my application is using Spring but the classes I need to "check" are not spring managed - also, I'd like to avoid changing the server start options to enable Spring annotation based run time weaving.
EDIT:
The classes I have to enforce the code on are Akka Typed Actors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 Spring,您是否考虑过将上下文设置为线程范围的 bean?如果这是通过 HTTP 请求,您可以在 bean 上使用 scope="request",Spring 将为您管理事务(包括将请求范围的 bean 传递给单例)。
您可以轻松创建更通用的线程范围。
If you're using Spring, have you considered making the context a thread-scoped bean? If this is through a HTTP request, you can use scope="request" on the bean and Spring will manage things for you (including passing a request-scoped bean to a singleton).
You can easily create a more general thread scope.
PMD 是一个不错的选择。此外,您可以将其与 IDE 集成,所有开发人员都会收到通知。
另一种选择是在构建过程中添加一些步骤,该步骤将使用某些正则表达式(或 Java 解析器 - PMD 也有一个)修改源代码,或者使用 ASM 或 JavaAssist 等库添加一些字节代码生成,这些库将后处理您的代码。编译后的代码。
如果您可以使用 AspectJ,那么您还可以在编译类文件后使用它来后处理它们以检查/添加一些代码。
如果您可以使用某些工厂实现来控制此类的创建,那么您可以围绕创建的实例创建动态代理。
PMD is a good option. Besides you can integrate it with IDE and all developers will be notified.
Another option is to add some step to your build process that will either modify the source code using some regular expression (or Java parser - PMD has one as well) or add some byte code generation using libraries like ASM or JavaAssist that will post process your code after it is compiled.
If you can use AspectJ then you can also use that to post-process your class files after they are compiled to check/add some code.
If you can control this class creation using some Factory implemetation, then you can create a dynamic proxy around the created instances.