Wednesday, December 9, 2020

Inversion of Control in Spring

So a major principle of software engineering is programming to an interface. Basically this means when creating objects we should create them based on the Abstract class and only instantiate this object with its implentation class.


Coach Obj = new TrackCoach();


Above is an example of a Coach Abstract Class object being instantiated with an implentation Class Object. Of course Obj cannot be instantiated with anything else if declared as an abstract class. So the benefit to this is if we want to apply a new implentation, we simply replace TrackCoach(); with say SoccerCoach(); And this is where Inversion of Control comes in!

Inversion of Control

Instead of manually adjusting the POJO(Plain Old Java Object) e.g TrackCoach(), we can use three methods available in Spring:

  • Using an XML configuration file along with the ClassPathXmlApplicationContext class
  • Using Java Annotations
  • Using Java code
With the XML configuration file we create a bean tag in the configuration file which is an xml file located in the Application folder available to all packages within the applciation. Here, we specify the id and class attribute of an implentation class! Now in our app

In config file:
<bean id = "myCoach"
class= "com.rogersentongo.springdemoapp.SoccerCoach">


In main application:
//We create a Spring container object that contains the config file passed as an argument using its name

ClassPathXmlApplicationContext context = new  ClassPathXmlApplicationContext("applicationcontext.xml")

//Instantitate Coach object with the bean id
Coach theCoach = context.getBean("myCoach", Coach.class)

Now we can use any overriden function of the implementation described by myCoach id! All we have to do is change the class attribute in the bean tag in order to change the implementation. 

No comments:

Post a Comment