问题
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