What is the advantage of ApplicationContextAware over Setter Injection.Through Setter Injection also we can get beans from Spring Container.
4 Answers
With ApplicationContextAware
you get reference to the current context so you can edit it, for example add or remove beans. Generally this is a bad idea, except in some testing scenarios.
Spring also emphasizes that with ApplicationContextAware
you are more dependent on Spring framework than with a simple POJO with setters.

- 7,539
- 4
- 51
- 81
-
Incase we need many utility beans in our class, which one would you prefer.Wont the class look complex by writing lots of setters/getters – cooper Jan 20 '13 at 19:02
-
In case you need many utility beans you should consider whether your bean has the correct role (if it does too many things / has too many responsibilities) or is your utility beans separated to good logical groups. This way you should be able to cut down unnecessary dependencies. I can think of any reason to `ApplicationContextAware` in any production bean. – vertti Jan 21 '13 at 04:59
You should not use ApplicationContextAware
unless you really need it. If you can support all your business needs with setter/field/constructor injection, don't use ApplicationContextAware
.
Some might be tempted to use ApplicationContextAware
in order to fetch fresh instance of prototype scoped bean (actually BeanFactoryAware
is enough). But there are better tools for that, namely lookup-method
.

- 334,321
- 69
- 703
- 674
It is two different patterns. When you use ApplicationContextAware
you implements Service Locator pattern, but setter injection refers to a Dependency Injection pattern. Latter is more preferable when developing low-coupled applications.
The difference between these two patterns is described here or here
In most scenaios, setter injection is totaly enough, which provides a better solution helping you maintain relations among instances. Because the classes don't depend on the container directly, that is to say, they are Pojos and don't need to know the existence of the container, which will bring lots of convenience to the Unit tests and future imigration.
If you really need to get something out of the container, making some enhancement for certain kind of beans for example, then it's time to use ApplicationContextAware. In general, getting dependences manually in class by implementing ApplicationContextAware is not recommended, especially for business objects. they should not be responsible for the assembling of themselves'.

- 957
- 6
- 9