【问题标题】:Find annotated classes inside OSGi bundle with Spring?使用 Spring 在 OSGi 包中查找带注释的类?
【发布时间】:2013-10-07 11:35:21
【问题描述】:

我想在 OSGi 包中查找所有使用我的自定义注释进行注释的类,
必须在包本身或从另一个包中进行实际扫描
我曾尝试使用ClassPathScanningCandidateComponentProvider,但它会导致异常:

java.io.FileNotFoundException: URL [bundleresource://38.fwk29597962/my/base/package/] cannot be resolved to absolute file path because it does not reside in the file system: bundleresource://38.fwk29597962/my/base/package/

我 99% 确定,reflections 或其他扫描库之类的解决方案也不起作用,现在不记得为什么了

我可以像这样配置组件扫描:

<context:annotation-config />
<context:component-scan base-package="my.base.package" use-default-filters="false">
    <context:include-filter type="annotation" expression="path.to.my.annotation"/>
</context:component-scan>

并从 bean factory 中获得我需要的东西,但这需要将 @Scope("prototype") 添加到我所有带注释的类中,因此 spring 默认情况下不会创建单例等。
有更好的解决方案吗?

-我的注释类没有 @Component 或任何与 spring 相关的东西
-osgi 框架(eclipse Equinox 3.8)嵌入在 Web 应用程序中
- 使用 spring 3.2.3 和 gemini-blueprint 2.0.0.M02

【问题讨论】:

    标签: spring annotations osgi spring-dm


    【解决方案1】:

    如果您准备在构建时而不是在运行时进行扫描,那么 bnd 有一个相当不错的宏可供您使用:

    MyAnnotated-Classes: ${classes;CONCRETE;ANNOTATION;org.example.MyAnnotation}
    

    ...这将在清单中生成一个MyAnnotated-Classes 头,其中列出了捆绑包中具有@MyAnnotation 的所有类。现在在运行时扫描此标头很简单。

    这种方法是对运行时类路径扫描的重大优化。运行时扫描也可能不可靠,因为您需要捕获 Bundle-ClassPath 的内容,但要避免任何导入/必需的类。

    【讨论】:

    • bundle.adapt(BundleWiring.class).listResources("/", "*.class", LISTRESOURCES_LOCAL | LISTRESOURCES_RECURSE) 可用于扫描包的 Bundle-ClassPath 以查找所有 .class 资源。
    • @Neil Bartlett 很高兴知道这一点,但我想出了另一个想法,我将使用注释处理器处理带注释的类,同样在构建时,我可以在 maven 编译器插件中轻松定义它,处理器将生成我需要的文件,因为它不仅仅是一个列表,稍后该文件将包含在 jar 中
    • @BJ Hargrave 你忘了从 osgi 4.3 中添加它
    • 我刚刚链接到最新的 javadoc。
    猜你喜欢
    • 2012-01-15
    • 2012-04-14
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2014-11-18
    相关资源
    最近更新 更多