注入到通过反射创建的类
我想使用我自己的 Velocity 框架中的 StringResourceRepository 实现。但是我需要在这个实现中使用注入的@Repository。问题是 Velocity 通过反射创建我的类,然后在初始化期间使用它的方法。由于存储库引用为空 - 没有注入任何内容。在不修改 Velocity 源代码的情况下,我可以用这段代码做什么?
似乎一种可能性是实现自己的 StringResourceLoader,但我想知道还有其他方法可以解决这个问题吗?
I wanted to use my own implementation of StringResourceRepository from Velocity framework. However I need to use in this implementation injected @Repository. Problem is that Velocity creates my class via reflection, and then uses its method during initialization. Because of that Repository reference is null - nothing is injected. What can I do with this code without modifying Velocity source code?
It seems that one possibility is to implement own StringResourceLoader, but I'm wondering is there any other way to resolve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下@Configurable注解,这使得spring能够将依赖项注入到不是由spring直接实例化的对象中。您需要启用aspectj weaving才能使其工作。
Take a look at @Configurable annotation, this enables spring to inject dependencies into objects that are not directly instantiated by spring. You will need to enable aspectj weaving for this to work.
您可以让 Spring 在您自己创建的实例或第三方库创建的实例上进行自动装配,如下所示:
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
wac.getAutowireCapableBeanFactory().autowireBean(对象);
这需要手头有 ServletContext,因为没有包含根 WebApplicationContext 的全局静态。
或者,如果您在 FactoryBean 中设置速度,则可以实现 WebApplicationContextAware 并以这种方式获取 AutowireCapableBeanFactory。
另一种选择是使用 AspectJ 和加载时编织。
You can have Spring do autowiring on an instance you create on your own or one created by a third party library like this:
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
wac.getAutowireCapableBeanFactory().autowireBean(object);
This requires having the ServletContext at hand since there's no global static containing the root WebApplicationContext.
Or if you're setting up velocity in a FactoryBean you can implement WebApplicationContextAware and get the AutowireCapableBeanFactory that way.
Another option is using AspectJ and load time weaving.