Java Spring- ApplicationContext Class
Hello friends, look at the code below and let us discuss something quite interesting.
ApplicationContext context = new ClassPathXmlApplicationContext(“resources/config.xml”);
Triangle triangle = (Triangle)context.getBean(“triangle”);
triangle.draw();
I want us to talk about the ApplicationContext class of java’s spring framework.
Am sure at some point you have wondered the magic behind spring helping java developers achieve dependency injection. One of the questions I always asked myself is how does spring get to know all the classes in my application so that it can create objects out of them?
Simple, you prepare an xml file and load it at initialization of the application. Exactly the first line of code in the snippet I shared above.
ApplicationContext context = new ClassPathXmlApplicationContext(“resources/config.xml”);
So I am telling spring, hey look I need you to read the xml file by the name “config.xml” in the folder called resource. And guess what is in that file?
<?xml version=”1.0" encoding=”UTF-8"?>
<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN 4.0//EN”
“http://www.springframework.org/dtd/spring-beans-4.0.dtd">
<beans>
<bean id=”triangle” class=”com.davies.springcore.Triangle” autowire=”byName”>
</bean>
<bean id=”A” class=”com.davies.springcore.Point”>
<property name=”x” value=”0" />
<property name=”y” value=”30" />
</bean>
<bean id=”B” class=”com.davies.springcore.Point”>
<property name=”x” value=”40" />
<property name=”y” value=”0" />
</bean>
<bean id=”C” class=”com.davies.springcore.Point”>
<property name=”x” value=”0" />
<property name=”y” value=”0" />
</bean>
</beans>
configuration of beans. Beans here referring to the classes I will be using. Just like that and spring knows all your classes. So any time you tell it hey I need to create an object of class Point. It already knows where the class is and how to create it for you. Then it hands it over to you for use.
By the time the first line executes, spring already knows everything. What we can call the context of your application. I guess the reason as to why it is referred to as ApplicationContext. What is now remaining is the access to the objects through a method called getBean(“beanName”); which requires the bean name.
Guys, am sure you now know why that class is termed ApplicationContext class. Simply that.