Spring 自定义注释 - 如何使其成为库的一部分?
我创建了一个自定义注释(在 Spring 3.05 中),效果很好。我想采用该代码并将其作为库的一部分,打包在 jar 文件中,这样我就不必在我编写的每个 Web 应用程序中包含自定义注释代码。
但是,我无法让 Spring 对注释进行操作。我的库 jar 位于我的 Web 应用程序的类路径中,我尝试在 applicationContext.xml
中扫描它:
<context:component-scan base-package="my.annotation.pkg" />
用我的自定义注释注释的字段仍然为空。
理想情况下,我希望这个工作只需最少的麻烦和配置,但到目前为止我还没有取得任何成功。
当我的自定义注释是外部库的一部分时,我缺少 Spring 连接的哪一部分来识别它?
更新
这是我“解决”它的方法......只需更仔细地阅读即可。在每个上下文文件(即 applicationContext.xml、dispatch-servlet.xml)中,我添加了以下行:
<bean class="my.annotation.CustomInjector" />
...其中我的 CustomInjector 实现了 BeanPostProcessor。我基于此博客文章中的代码: 使用 Spring 实现 Seam 风格的 @Logger 注入。
作者说我需要完全按照我所做的去做,因为我没有彻底阅读,这对我来说很糟糕。但是,为什么需要添加该 bean 定义呢?也许 Spring 注释在底层的配置类似 - 我只是不明白为什么在类路径上有 jar 文件是不够的。
I've created a custom annotation (in Spring 3.05) that works great. I'd like to take that code and make it part of a library, packaged in a jar file, so I don't have to include my custom annotation code in each web app I write.
I'm unable to get Spring to act on the annotation, however. My library jar is in my web app's classpath and I tried scanning for it in applicationContext.xml
:
<context:component-scan base-package="my.annotation.pkg" />
The field annotated with my custom annotation continues to be null.
Ideally I'd like to this to just work with a minimum of fuss and configuration, but so far I haven't had any success.
What part of Spring's wiring am I missing to get my custom annotation recognized when it's part of an external library?
Update
Here is how I "solved" it...just had to read a little more closely. In each context file (i.e. applicationContext.xml, dispatch-servlet.xml) I added the line:
<bean class="my.annotation.CustomInjector" />
...where my CustomInjector implements BeanPostProcessor
. I based this on the code at this blog post: Implementing Seam style @Logger injection with Spring.
The author says I needed to do exactly what I did, so bad on me for not reading thoroughly. Why, though, is adding that bean definition required? Maybe Spring annotations are configured similarly under the hood - I just don't get why having the jar file on the classpath isn't enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的自定义注释是否使用 进行注释@Component 注释?来自 Spring参考手册:
或者,您可以添加自定义 include-filter 添加到 XML 配置中的
component-scan
元素。Is your custom annotation annotated with the @Component annotation? From the Spring reference manual:
Alternatively, you could add a custom include-filter to the
component-scan
element in your XML configuration.