Close

Spring - Making Bean ApplicationContext aware

[Updated: Feb 8, 2017, Created: Jan 2, 2016]

We can inject spring ApplicationContext as a bean into any bean. By doing so, we are effectively making our bean ApplicationContext aware. Our bean then programmatically can retrieve other beans by calling ApplicationContext.getBean()or retrieve any resources by calling applicationContext#getResource()

Using this approach, we can solve the problem of injecting a prototype bean into singleton bean as mentioned in the last topic.

We can inject ApplicationContext as bean using @Autowire annotation or by implementing spring ApplicationContextAware interface.

In the following example, we are going to modify our last example to demonstrate the recommended @Autowire approach



Example Project

Dependencies and Technologies Used:

  • Spring Context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.0.4

Using Application Context In Beans Example Select All Download
  • application-context-aware
    • src
      • main
        • java
          • com
            • logicbig
              • example

Output:

   Hi, the time is 2016-01-02T18:11:11.541
   Hi, the time is 2016-01-02T18:11:12.588

Disadvantage of Injecting ApplicationContext in the Beans

Injecting ApplicationContext, couples the application code to Spring API. Secondly, it does not follow the Inversion of Control principle as we are not letting Spring to inject the dependencies but we are asking the container to give us the dependencies. In some situation this capability might be useful, e.g. some bean taking care of some sort of integration to some other framework etc. However, in general we should avoid this approach for fixing narrower scoped bean injection problem

In next example we are going to see how we can use Lookup method injection to solve narrower scoped bean injection problem.

See Also