Can I inject properties to third-party beans?

倖福魔咒の 提交于 2019-12-24 15:27:37

问题


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

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

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

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


回答1:


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

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 will handle all the beans you instantiate with the bean factory. You are on your own with all others created using new.



来源:https://stackoverflow.com/questions/37346511/can-i-inject-properties-to-third-party-beans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!