Spring Core | Spring Container

In our previous post, we learned how we leverage Dependency Injection to design loosely coupled application which enables objects to focus on their business logic and make application’s components test friendly. I suggest you go through it for more better understanding. What is Dependency Injection?

Spring Container

In order to enable dependency injection, we need some way to wire these objects together so that they can work collaboratively to perform some business logic. But before we dive into wiring we need to understand where do these objects will be hanging out in our application? In Spring-based application, objects live in a spring container.

spring-container
Image Source: Screenshot from Spring In Action

In the above figure, the container creates objects, wire them together, configures them and manages their complete lifecycle from birth to death. Spring comes with several implementations of containers which can be categorized into two different types.

  • Bean factories: These are the simplest type of container, providing basic support for DI.
  • ApplicationContext: These are built on the notion of bean factories. It adds some extra functionality as compared to its parent class.

Understanding the Application Context

Spring comes with different flavors of Application Context. Here are few which we commonly use:

  • AnnotationConfigApplicationContext: Loads a Spring application context from one or more Java-based configuration classes.
  • ClassPathXmlApplicationContext: Loads a context definition from one or more XML files located in the classpath.
  • FileSystemXmlApplicationContext: Loads a context definition from one or more XML files located in filesystem.
  • AnnotationConfigWebApplicationContext: Loads a spring web application context from one or more Java-based configuration classes.

In modern Java-based applications, using annotations has become a common standard so we will be mostly using annotation to configure components in this tutorial and loading it using AnnotationConfigApplicationContext.

ApplicationContext context = new AnnotationConfigApplicationContext(com.lifeinhurry.persons.config.StudentConfig.class);

With an application context in hand, you can retrieve beans from the Spring container by calling the context’s getBean() method.

Conclusion

In this post, we learned about spring containers, their types and different ways to load context definitions. Now since we understand what is spring container and how to use it, we will learn how to define Java objects (beans) and how to wire them in our next post.