Concepts Before starting SpringBoot

Learning any technology and framework is easy , mastering and having a clear understanding is difficult. This articles aims to discuss some important concepts before starting Spring Boot.

Framework

Imagine I asked you to cut a single piece of paper measuring 5m by 5m. You would likely do that without any extra tools. But now, suppose I asked you to cut 1,000 pieces of paper with the same dimensions. Instead of measuring and cutting each piece individually, you’d probably create a 5m by 5m frame to simplify and speed up the process. This frame would allow you to cut all 1,000 pieces efficiently, without repeatedly performing the same measurements.

Essentially, you’ve created a framework – a tool designed to perform a specific task consistently and efficiently. Rather than repeating the same actions for similar tasks, the framework consolidates everything needed into one convenient package, offering a level of abstraction that simplifies the process for various applications.

In computer programming, a software framework operates on the same principle. It provides an abstraction layer consisting of common code with generic functionality, which can be customized or extended by user-defined code to meet specific needs. Unlike regular software libraries, frameworks are reusable structures with a well-defined Application Programming Interface (API). They differ from typical libraries in that they offer a more comprehensive and structured approach, enabling efficient development by integrating commonly needed functionalities into a unified system.

Spring vs SpringBoot

Everyone starting Springboot comes across a thought ie Do I need to know Spring ? or What is difference between them. So, here is the answer

Spring framework is a java EE framework that is used to build applications. Its goal is to make Java EE (Enterprise Edition) development easier, allowing developers to be more productive. Spring framework requires too many lines of code (boilerplate code) even for minimal tasks and lots of configurations that have to been done manually

The main or primary feature of the Spring Boot is Autoconfiguration( Simply described, Spring Boot autoconfiguration is a method of automatically configuring a Spring application based on the dependencies found on the classpath.)
Autoconfiguration can speed up and simplify development by removing the need to define some beans that are part of the auto-configuration classes.

SpringBoot takes out all pain point of Spring and it simplifies development.

Inversion of Control (IOC)

In software engineering, inversion of control (IoC) is a design principle in which custom-written portions of a computer program receive the flow of control from a generic framework.

Callbacks, schedulers, event loops, and the template method are examples of design patterns that follow the inversion of control principle, although the term is most commonly used in the context of object-oriented programming.

The Inversion-of-Control (IoC) pattern, is about providing any kind of callback, which “implements” and/or controls reaction, instead of acting ourselves directly (in other words, inversion and/or redirecting control to the external handler/controller).

I would suggest to read more on Wiki and this thread

Spring Beans

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container

Dependency Injection

Dependency injection (DI) is a specialized form of IoC, whereby objects define their dependencies (that is, the other objects they work with) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The IoC container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes or a mechanism such as the Service Locator pattern.

Constructor, Setter and Field Injection

Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency. Calling a static factory method with specific arguments to construct the bean is nearly equivalent, and this discussion treats arguments to a constructor and to a static factory method similarly. The following example shows a class that can only be dependency-injected with constructor injection:

public class SimpleMovieLister {

	// the SimpleMovieLister has a dependency on a MovieFinder
	private final MovieFinder movieFinder;

	// a constructor so that the Spring container can inject a MovieFinder
	public SimpleMovieLister(MovieFinder movieFinder) {
		this.movieFinder = movieFinder;
	}

	// business logic that actually uses the injected MovieFinder is omitted...
}

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or a no-argument static factory method to instantiate your bean.

The following example shows a class that can only be dependency-injected by using pure setter injection. This class is conventional Java. It is a POJO that has no dependencies on container specific interfaces, base classes, or annotations.

public class SimpleMovieLister {

	// the SimpleMovieLister has a dependency on the MovieFinder
	private MovieFinder movieFinder;

	// a setter method so that the Spring container can inject a MovieFinder
	public void setMovieFinder(MovieFinder movieFinder) {
		this.movieFinder = movieFinder;
	}

	// business logic that actually uses the injected MovieFinder is omitted...
}

Bean Scopes

There are six types of spring bean scopes

  1. Singleton – (Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
  2. Prototype – Scopes a single bean definition to any number of object instances.
  3. Request – Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
  4. Session – Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
  5. Application – Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
  6. Websocket – Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

AOP – Aspect Oriented Programming

AOP addresses the problem of cross-cutting concerns, which would be any kind of code that is repeated in different methods and can’t normally be completely refactored into its own module, like with logging or verification. So, with AOP you can leave that stuff out of the main code and define it vertically like so:

function mainProgram()
{ 
   var x =  foo();
   doSomethingWith(x);
   return x;
}

aspect logging
{ 
    before (mainProgram is called):
    { 
       log.Write("entering mainProgram");
    }

    after (mainProgram is called):
    { 
       log.Write(  "exiting mainProgram with return value of "
                  + mainProgram.returnValue);
    }
 } 

aspect verification
{ 
    before (doSomethingWith is called):
    { 
       if (doSomethingWith.arguments[0] == null) 
       { 
          throw NullArgumentException();
       }

       if (!doSomethingWith.caller.isAuthenticated)
       { 
          throw Securityexception();
       }
    }
 }

And then an aspect-weaver is used to compile the code into this:

function mainProgram()
{ 
   log.Write("entering mainProgram");

   var x = foo();   

   if (x == null) throw NullArgumentException();
   if (!mainProgramIsAuthenticated()) throw Securityexception();
   doSomethingWith(x);   

   log.Write("exiting mainProgram with return value of "+ x);
   return x;
} 

Spring AOP

AOP is used in the Spring Framework to:

  • Provide declarative enterprise services.
  • Let users implement custom aspects, complementing their use of OOP with AOP.

Spring AOP is a big topic and out of scope for this article. Please check AOP-Concepts for more details

Spring MVC vs Webflux

The Servlet async model introduces an async boundary between the container threads (1 Servlet request/thread model) and the processing of the request in your application. Processing can happen on a different thread or wait. In the end, you have to dispatch back to a container thread and read/write in a blocking way (InputStream and OutputStream are inherently blocking APIs).

With that model, you need many threads to achieve concurrency (because many of those can be blocked waiting for I/O). This costs resources and it can be a tradeoff, depending on your use case.

With non-blocking code, you only need a few threads to process a lot of requests concurrently. This is a different concurrency model; like any model, there are benefits and tradeoffs coming with it.