Inversion of Control Container
Written by: Tom Spencer
Jun 26, 2022 — 3 min readInversion of Control
Spring IoC (Inversion of Control) Container is the core of the Spring Framework. There are two types of containers in Spring - the Bean Factory and the Application Context. ApplicationContext is an interface in the org.springframework.context package and is implemented by several classes. The ClassPathXmlApplicationContext is one such implementation.
Spring BeanFactory
Here is an overview of the classes provided by the BeanFactory:
- FileSystemXmlApplicationContext provides beans loaded through the full path.
- ClassPathXmlApplicationContext provides beans loaded through the CLASSPATH
- XMLWebApplicationContext and AnnotationConfigWebApplicationContext beans are loaded through the web application context.
- AnnotationConfigApplicationContext loads Spring beans from Annotation based configuration.
Spring BeanFactory and Dependent classes |
---|
Bean Factory vs Application Context
Spring provides two kinds of IOC container: XMLBeanFactory and ApplicationContext. I include an overview of the differences between the two below:
Bean Factory
- Bean instantiation/wiring
- Application Context
Application Context
- Bean instantiation/wiring
- Automatic BeanPostProcessor registration
- Automatic BeanFactoryPostProcessor registration
- Convenient MessageSource access (for i18n)
- ApplicationEvent publication
Bean Factory and Application Context |
---|
Practice Implementation
For practice we can build a very simple application using the ClassPathXmlApplicationContext. We start with a Salutation interface with a single method message:
We then implement two classes that implement this interface. Hello and Goodbye:
Next we create a simple Meeting class in order to print out our message:
This is solid. We may want to avoid using lots of new Hello() instances in our application. The Spring ApplicationContext allows us to access a single instance of the Hello class through the ClassPathXmlApplicationContext. Let's look at how to do this.
First add spring-context to our pom.xml so that we have access to the Spring ApplicationContext from the Spring Framework.
Next add a beans.xml file in inversion-of-control/src/main/resources. This will allow us to access the Hello class through the id hello in our Spring ApplicationContext. It helps here to think of the Spring ApplicationContext as a map of keys and values where our key is "hello" and the value is the Hello class.
Now we have access to the ApplicationContext through the ClassPathXmlApplicationContext we can get the hello bean we have created and access the message:
We should get the message "Hello!":
Extra practice
- Change the accessed class from Hello to Goodbye and print the message.
- Code is available here inversion of control