将 bean 注入 Spring 托管上下文之外的类 [英] Injecting beans into a class outside the Spring managed context

查看:20
本文介绍了将 bean 注入 Spring 托管上下文之外的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是我公司产品之一的最终用户.它不太适合集成到 Spring 中,但是我能够处理上下文并按名称检索所需的 bean.但是,我仍然想知道是否可以将 bean 注入到这个类中,即使该类不是由 Spring 本身管理的.

I'm an end-user of one of my company's products. It is not very suitable for integration into Spring, however I am able to get a handle on the context and retrieve the required bean by name. However, I would still like to know if it was possible to inject a bean into this class, even though the class is not managed by Spring itself.

澄清:管理某个类 MyClass 生命周期的同一个应用程序也管理 Spring 上下文的生命周期.Spring 对 MyClass 的实例一无所知,我想知道如何将实例提供给上下文,但无法在上下文本身中创建实例.

Clarification: The same application which is managing the lifecycle of some class MyClass, is also managing the lifecycle of the Spring context. Spring does not have any knowledge of the instance of MyClass, and I would like to some how provide the instance to the context, but cannot create the instance in the context itself.

推荐答案

您可以这样做:

ApplicationContext ctx = ...
YourClass someBeanNotCreatedBySpring = ...
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(
    someBeanNotCreatedBySpring,
    AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);

您可以在 YourClass 中使用 @Autowired 等来指定要注入的字段等.

You can use @Autowired and so on within YourClass to specify fields to be injected etc.

这篇关于将 bean 注入 Spring 托管上下文之外的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆