我可以向第三方bean注入属性吗? [英] Can I inject properties to third-party beans?

查看:85
本文介绍了我可以向第三方bean注入属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些类,这些类不是由Spring实例化的.例如,可以通过反序列化器或JavaFX实例化它们.

Suppose I have classes, which were instantiated not by Spring. For example, they can be instantiated by deserializer or by JavaFX.

我可以使用与编写Spring bean相同的方式编码这些类,并在以后将属性注入它们吗?

Can I code these classes in the same way I code Spring beans and inject properties into them later?

实际上,我想要一个例程,该例程将使用反射方式扫描类,找到其中的所有@Autowired批注并从应用程序上下文中注入值?

Actually, I would like a routine, which would scan class with reflection, find all @Autowired annotations in it and inject values from application context?

如果我拨打applicationContext.getBeanFactory().registerSingleton("myName", myBean),会发生这种情况吗?请注意,我不会将自己限制为单例.

Will this happen, if I call applicationContext.getBeanFactory().registerSingleton("myName", myBean)? Note, that I would no limit myself with singletons.

推荐答案

如果Spring未实例化bean,则您不能要求Spring注入依赖项或建议它们.

If beans are not instantiated by Spring, then you cannot ask Spring to inject dependencies or advise them.

这是我看到春季新手犯的一个常见错误.他们调用new来实例化带有注释的bean,并且不明白为什么不注入依赖项.

This is a common mistake I see Spring neophytes make. They call new to instantiate a bean with annotations and can't understand why their dependencies aren't injected.

Spring将处理您在bean工厂中实例化的所有bean.您自己一个人,所有其他人都使用new创建.

Spring will handle all the beans you instantiate with the bean factory. You are on your own with all others created using new.

这篇关于我可以向第三方bean注入属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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