I see that it is possible for both Spring beans and other regular classes to access the spring application context.
I’m wondering why would a class ever have to deal with Spring context. My understanding is that, in the main method, you bootstrap your application and everything from that point is wired by Spring.
If that is the case, main method should be the only place where you need ApplicationContext. What are the other genuine cases where you need Spring context to get your work done?
Usually beans don’t need to access
ApplicationContextdirectly.However, there are cases when direct access is necessary. For example:
To access a bean identified by its name at runtime:
To pass custom arguments to constuctor of
prototype-scoped bean at runtime:Note that if
Bean‘s constructor doesn’t need custom arguments to be passed at runtime, you can injectObjectFactory<Bean>instead.To trigger autowiring of third-party objects using
AutowireCapableBeanFactory.