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 a better understanding. What is Dependency Injection?
- 1 Spring Container
- 2 Understanding the Application Context
- 3 Conclusion
- 3.1 Spring Bean Scope
- 3.2 Resolve Ambiguity in Spring Beans
- 3.3 Spring Core | Bean & Wiring | Part-2
- 3.4 LEAVE A REPLY Cancel reply
- 3.5 Spring Bean Scope
- 3.6 Resolve Ambiguity in Spring Beans
- 3.7 Spring Core | Bean & Wiring | Part-2
- 3.8 Spring Core | Bean & Wiring | Part-1
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 applications, objects live in a spring container.
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.
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.