Spring Container – The A,B,C,D of Spring???
Spring Container for starters

Spring Container – The A,B,C,D of Spring???


Spring, simply what is?it?

Spring is a open-source framework for building enterprise level applications using Java. You can build all sorts of applications using Spring from web applications to RESTful services to enterprise applications.

It provides a lots of modules that can be used or not used depending on our purpose, vaguely it includes?:

  • Spring Core?: This is the core module of spring which provides Inversion of Control(IoC) container and Dependency Injection capabilities.

??Ok don’t worry about the terminologies used, these are the one’s we will discuss about in the rest of the article.

  • Spring MVC?: This is used when we want to build web applications and RESTful services
  • Spring Data?: This is used to work with data sources like databases, cloud storage etc.,

Ofcourse there a lot more but let’s not go down that path for today.

The Spring, Spring Boot confusion???

??It’s natural to get confused between Spring and Spring Boot.

Basically, as we discussed above, Spring provides lot of modules which developers needs to configure and manage themselves which can time consuming and complex.

Spring boot provides a pre-configured environment which reduces time and complexity to setup spring based applications. It provides simpler development experience to quickly develop, test and deploy.

??Just because Spring boot is easier to use that doesn’t mean that’s the better choice.

Spring provides finer controls over the modules which might useful in some applications, so it solely depends on the type of the application you are building.


The Spring container ??

So what problem does Spring container solve??

Let’s consider the example below, where I have two classes

    class Controller
  	  Service service = new Service();
  	  public void doTask(){
  	    service.executeBusinessLogic;
  	  }
  	}
  	
  
  	class Service{
  	  public void executeBusinessLogic(){
  	    // code business logic here 
  	    return;
  	  }
  	}        

So here in Controller class we are creating the object of Service class and using it’s methods in the Controller class.

In this scenario, Controller class depends on Service class hence Service class is called a dependency for Controller class.

??Creating objects and maintaining them by ourself’s causes a lots of problems.

There is tight coupling between these two classes as the reponsibility of Object creation and maintainence is taken care by our classes other than the actual responsibility of what our classes are supposed to do.

??Here it voilates the Single responsibility principles of SOLID.

Becuase of this tight coupling its difficult to modify and maintain the code. This is just one layer of dependency let’s say Controller class is dependent on Service class, Service class depends on another Service class and so on.. It quickly becomes a overwhelming and error prone.

Another main problem is testability, so let’s say you want to test only the Controller class independently, Since dependent Objects creation and maintainence is part of our logic hence that should also be tested along with our Controller class which doesn’t sound exactly like unit tests right?

??So basically Spring container takes care of these problems.

Spring container basically maintains all the dependencies for you, so that you can focus on your business logic.

Let’s see how to create a Spring Container. In the below code when we mark our main Spring class as @SpringBootApplication, it basically creates the container just before starting the application.

??Spring Container is also called as ApplicationContext.
No alt text provided for this image

Now Let’s come back to our main example, here’s how we code the same in Spring Boot:

    class Controller
	  @Autowired
	  Service service = new Service();
	  
	  public void doTask(){
	    service.executeBusinessLogic;
	  }
	}
	

	@Component
	class Service{
	
	  public void executeBusinessLogic(){
	    // code business logic here 
	    return;
	  }

	}        

Here we have marked Service class as @Component which Spring sees it as dependency to be injected somewhere else and creates a instance of it and keeps it in Spring Container.

In the Controller class we mark the dependency as @Autowired which Spring sees it as dependency to be injected, when the object of Controller class is being created.

The same has been represented below.

No alt text provided for this image

Hence Service object is a dependency for Controller object.

??Dependencies are also called as beans in Spring. Here after i hope you are comfortable with word beans.

Any class can be a bean in Spring – REST controller classes, Service classes, database classes so on..

Inversion of Control (IoC) & Dependency Injection (DI)

So what is Inversion of Control?

The responsibility of creating and maintaining objects is delegated to Spring, instead of me as a developer controlling them, Spring controls hence the name Inversion of Control since the control is inverted.

Voila ??

Dependencies are injected into respective objects by Spring, is that what Dependency Injection is??

Yes ??

There are 3 types of dependency injection:

  • Field based DI — The one we used in the above example is called Field based DI.
  • Constructor based DI — The injection of dependencies happen via the constructor.

    @Component
	public class MyComponent {
	    
	    private final MyDependency myDependency;
	    
	    public MyComponent(MyDependency myDependency) {
	        this.myDependency = myDependency;
	    }
	    
	}        

  • Setter based DI — The injection of dependencies happen via a setter method.

    @Component
	public class MyComponent {
	    
	    private MyDependency myDependency;
	    
	    @Autowired
	    public void setMyDependency(MyDependency myDependency) {
	        this.myDependency = myDependency;
	    }
	    
	}        
?? Why so many types, to confuse us? NO.

Dependencies can be optional or mandatory.

In the above example we require the Service object in our Controller class for our Controller object to be functional hence thats a mandatory dependency.

There will be cases where in we have dependencies but they are not mandatory for the class to function those are optional dependencies.

??As a thumb rule, we use Constructer based DI for mandatory dependencies, Setter based DI for optional dependencies, Field based DI can be used for both.

Bean configuration in?Spring

We have seen how dependencies are managed in Spring Boot lets see how the same can be done in Spring.

We would be maintaining separate configurations for each class in XML based configuration or Java based configuration.

    // At Controller
	<bean id=”driverController" class="org.fs.controller.DriverController">
	  <property name=”driverService" ref=”driverService"/>
	</bean>
	
	// At Service 
	<bean id="driverService"class="org.fs.service.DriverService">
	</bean>        

Here bean indicates that it can be used as a dependency by Spring, list of properties inside bean are the dependencies needed inside that bean.

This is just to give a gist on how it will be done in Spring.

Bean scopes

Since we are giving the control of Objects to Spring there should be a way in which we control how beans should behave through it’s lifecycle.

??That’s where bean scopes come in.

There are basically 6 bean scopes, let’s discuss couple of them on a high level.

  • Singleton — Singleton bean scope is the default scope for any bean in Spring Container. Here only one instance of bean is maintained per Spring Container and that instance would be injected in all the consuming objects.

The same has been represented below.

No alt text provided for this image

  • Prototype — A instance of bean would be created per Injection. The same has been represented below.

No alt text provided for this image
??When do we use Singleton vs Prototype??

We would use singleton when we don’t want to maintain any state in our beans called stateless beans, we would use Protype when we need to maintain state called stateful beans.

The rest of the bean scopes are Request, Session, Application, Web Socket.

That basically concludes the Spring Container, I will come back with next set of concepts related to Spring for starters.


Thank you for reading! If you enjoyed it, please do like and share.

Hello Paul... We post 100's of job opportunities for developers daily here. Candidates can talk to HRs directly. Feel free to share it with your network. Visit this link - https://jobs.hulkhire.com And start applying.. Will be happy to address your concerns, if any

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了