Java - 使用注释自动实现服务定位器模式
Spring几乎提供了我想要的。在Spring中,您可以简单地使用@Component注释类,然后使用“context:component-scan”让Spring自动搜索组件。然后,您可以创建一个应用程序上下文并调用 getBean(String, Class) 来获取任何接口或类的实现。
例如,如果我有一个接口“Mp3Service”,并且我想注册一个名为“InternetMp3Service”的新实现,我所要做的就是将 @Component 注释添加到类定义中。
对我来说唯一的问题是我想在小程序中使用所有这些,因此我得到了权限“accessDeclaredMembers”的 java.lang.RuntimePermission 异常。我不想签署小程序,也不想为 bean 创建显式配置。
我正在寻找的是一个框架/库,它将在编译/构建时遍历注释并创建一个可以在运行时读取的配置。
例如,如果这里没有出现任何问题并且我认为这是值得的,我可以编写自己的程序来抛出所有类并查找某个注释,然后创建一个 spring xml 配置文件。然而,我认为现在有人可能会使用已经可用的东西。
谢谢。
Spring almost provides what I want. In Spring you can simply annotate classes with @Component and then use "context:component-scan" to have Spring automatically search for components. Then later you can create an application context and call getBean(String, Class) to get an implementation of any interface or class.
For example, if I have an interface "Mp3Service" and I want to register a new implementation called "InternetMp3Service", all I have to do is add the @Component annotation to the class definition.
The only problem with this for me is that I want to use all of this in an applet and so I get a java.lang.RuntimePermission exception for the permission "accessDeclaredMembers". I don't want to sign the applet and I don't want to have to create an explicit configuration for the beans.
What I'm looking for then is a framework/library that will go through the annotations at compile/build time and create a configuration that can then be read at run-time.
For example, if nothing comes up here and I decide it's worth the trouble, I could write my own program to go throw all the classes and look for a certain annotation and then create a spring xml configuration file. However, I thought someone might now of something already available.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个用例实际上是有道理的,但我确信还没有人实现它。
我看到有两种方法:
a)使用 Pluggable注释处理API。这里的问题是 Spring 在扫描注释时执行非常高级的逻辑,您可能必须为注释处理器重新实现它。
b) 使用一个主类来完成 Spring 所做的事情(查看 org.springframework.context.annotation.ComponentScanBeanDefinitionParser 的源代码以了解从哪里开始)。将主类连接到 Maven 或 ant 构建,使其在编译时自动执行。这里的问题是您必须处理已编译的类,而不是源代码,因此您的服务定位器类在编译时将不可用。
This use case actually makes sense, but i'm sure nobody has implemented it yet.
I see two ways of doing it:
a) using the Pluggable annotation Processing API. The problem here is that Spring does very advanced logic when scanning for annotations, and you will probably have to re-implement that for the annotation processor.
b) using a Main Class that does what Spring does (have a look at the source of org.springframework.context.annotation.ComponentScanBeanDefinitionParser to get an idea of where to start). Wire up the main class to a maven or ant build to have it automatically executed at compile-time. The problem here is that you will have to work on compiled classes, not on sources, so your Service Locator class won't be available at compile time.