I am trying to learn some spring through reading the broadLeaf
.
Why some broadLeaf
use ApplictionContext.getBean() instead of @Autowired annotation?
你好!
Fundamentally they are intended to do the same thing which is getting a bean from the spring container (i.e ApplicationContext
) to use. You can think that @Autowired
will actually do the work done by ApplictionContext.getBean()
behind scene.
The differences are that when using ApplictionContext.getBean()
, developers are in charge of the whole process by themselves .They have to make sure they get the correct beans by manually invoke getBean()
with the correct parameters. But when using @Autowired
, developer don't need to do this process manually. Instead , they just need to declare what beans they want and Spring will get these beans for them. So this is somehow the spirit of Inversion Of Control (IOC) as the responsibility of controlling of the above mentioned tasks are inverted and shifted from developers to the framework.
As best practices , we should always use @Autowired
first. Not only it is more convenient , less error prone , but also our domain codes will not depend on the Spring framework class (i.e ApplictionContext
) , which make our codes look more clean.
If you come to the situation that @Autowired
cannot fulfil your requirements as you need to have the most flexibility to get a bean , then check if ApplictionContext
can help you at that time.