是否可以自动装配在 ApplicationContext 外部创建的依赖项?
我有一个使用 JAXRS 来使用注释映射 Restlet 资源的应用程序。然而,我拥有的唯一入口点本质上是在应用程序配置中定义资源类列表。这些类由 Restlet 或 JAXRS 实例化,因此我无法将它们放入我的 ApplicationContext
中。有没有办法让 Spring 扫描类路径并根据需要自动装配新实例?我已经尝试过使用如下所示的方法:
@Autowired
private SessionFactory sessionFactory;
不幸的是,它并没有真正起作用。有办法做到我在这里所说的吗?
I've got an application which uses JAXRS to map Restlet resources using annotations. However, the only entry point I have is essentially defining a list of resource classes in the application configuration. These classes are instantiated by Restlet or JAXRS, so I have no way to put them in my ApplicationContext
. Is there a way to have Spring scan the classpath and autowire new instances as necessary? I've already tried using something like below:
@Autowired
private SessionFactory sessionFactory;
Unfortunately, it doesn't really work. Is there a way to do what I'm talking about here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 AspectJ 来依赖注入在您无法控制的情况下创建的 bean,或者如果您使用 new 创建对象。您可以阅读有关 Spring 文档的更多信息: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-using-aspectj
本质上你会做什么是将@Configurable注释添加到您想要作为注入目标的类。您还必须在 Spring xml 中启用它。最后,您必须在编译时编织或运行时编织之间做出决定。同样,您可以从 spring 文档中获得帮助。
加载时编织: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-aj-ltw
如果你使用maven,你可以检查这个Stackoverflow设置编译时 AspectJ 的问题: 为什么不AspectJ 编译时编织 Spring 的 @Configurable 工作?
You can use AspectJ to dependency inject your beans that are created out of your control, or if you create objects using new. You can read more on Springs documentation: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-using-aspectj
Essentially what you will do is add @Configurable annotation to the class that you want to be target of injection. You also have to enable it in Spring by having in your Spring xml. Lastly you have to decide between compile time weaving or runtime weaving. Again you can get help from spring documentation.
Loadtime weaving: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-aj-ltw
If you use maven you can check this Stackoverflow question for setting up compile time AspectJ: Why doesn't AspectJ compile-time weaving of Spring's @Configurable work?
ApplicationContext.getAutowireCapableBeanFactory().autowireBean(object)
将把所有依赖项注入到该对象中。ApplicationContext.getAutowireCapableBeanFactory().autowireBean(object)
will inject all dependencies into the object.