Skip to main content

Spring Boot Overview

What is Spring ? 

Spring Framework is an application framework and inversion of control container (IOC). 

What is inversion of control ?

By name only you can predict that it inverses the control , but question is control of what ? And the answer to this is creation of Beans. To understand this lets understand Association which is of 2 types 1)Aggregation and 2) Composition

In Aggregation we will have instances of one class to other class and in Composition also its same, only difference is that in composition it will be more dependent to each other while in Aggregation both classes will be independent .

 But in both the scenarios they need instances of each other. Let's consider below example before Spring how we used to associate a class into another class.

class Student{

String name;
String id;
Address Address=new Address();
int mobile ;
}

class Address{
int houseNumber;
String roadName;
String landMark;
String district;
String state;
int pin;
}

In above example we have used new keyword to create a Address class Object inside Student class.

This is what spring has reversed and taken the control of creating Object of any class and will keep it inside IOC container and inject wherever it is required by intercepting annotation @Autowired.

class Student{

@Autowired
Address Address
;

String name;
String id;
int mobile ;
}

class Address{
int houseNumber;
String roadName;
String landMark;
String district;
String state;
int pin;
}

As bean will be created by Spring so to do some operation in between bean's lifecycle we have some annotation which can be use based on our requirement like for init() method  we have @PostContruct and for destroy method we have @PreDestroy

What is the Advantage of using Spring ? 

Before Spring we used to create our own servlet by extending a class HTTPSERVLET and then we will override methods like doGet(HttpServletRequest, HttpServletResponse) or doPost(HttpServletRequest, HttpServletResponse) and inside these methods we will have our request/response logics and in web.xml file we will write each servlet mapping with desired path.

Example :

<web-app>
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>com.test.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>

  Same thing has been done by Spring where all these Servlet creation and request/response mapping will be done by Spring along with Embedded Tomcat Server. And to do so SPRING has created its own front controller to handle all the incoming request and named it as DispatcherServlet . This is main unique controller to handle all the incoming request and Dispatch it to the right custom controller created by us.


So we got the idea behind Spring what it does and how it's making a developer task easy by creating servlet and servlet mapping internally based on Annotation. Now lets understand between various variety of Spring.

As explained above we can also say that SPRING is abstracted framework and SPRING BOOT is more abstracted framework of SPRING MVC. How ?

Spring boot is implementing a lot of things internally which is not required to be configured by developer only dependency details should be given in pom.xml of spring boot application and spring will download the dependency jars and create the respective beans in backend at the time application start.

 For Example Spring MVC stands of Model,View and Controller , in which model and view should be configured by developer like for view part we have a class called InternalResourceViewResolver and this class has 2 property prefix and suffix , prefix is the path of view files and suffix is the type of view files. For example if response in SPRING MVC is home and prefix is : apps/file/view/ and suffix is jsp then home.jsp will be searched in this folder : apps/file/view/home.jsp and same will be displayed to client.

In spring boot we have annotation called @RestController which a combination of 2 spring annotation.

@Controller
@ResponseBody 
    Here no need of defining response path and type externally , it will return a json response automatically. if we want to change the type of return from json to xml then in pom.xml we need to put below dependency and  we can use produces to define the type of return like json , xml etc.

<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Now while hitting the request in Header we need to add one key called Accept and mention the type you are accepting like application/xml or application/json and you will get your results in same format as mentioned. This is called Content negotiations .



Next annotation is @SpringBootApplication , this annotation is also a combination of 3 spring annotation

@Configuration
@EnableAutoConfiguration
@ComponantScan

 Instead of mentioning all 3 annotation just mentioned  @SpringBootApplication, and spring will do all the jobs of these 3 annotation.

So till now we have noticed based on the annotation spring boot is smart enough to predicate and try to make the things simpler for developer.

 Just like annotation, for all other things just put your dependency in pom.xml and spring boot will create the objects and do the default required configuration automatically

How spring boot is able to do this ?

  The main keyword is behind this magic is Condition and Conditional interface . You can go to the META-INF/spring.factories file of spring-boot-autoconfigure.jar present in your spring boot application under external libraries. You will be able to see Main class of each dependency of pom.xml . 

Auto-configuration classes uses below annotation and all are been extended from condition interface which has below method :

        @FunctionalInterface
        public interface Condition         
        {
            boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
        }


Some important annotation used by Spring
  1. @SpringBootApplication (@Configuration,@EnableAutoConfiguration, and @ComponentScan)

  2. @ConditionalOnClass and @ConditionalOnMissingClass 
  3. @ConditionalOnBean and @ConditionalOnMissingBean > @ConditionalOnBean(name = "dataSource")
  4. @ConditionalOnProperty > @ConditionalOnProperty( name = "usemysql", havingValue = "local" )
  5. @ConditionalOnResource > @ConditionalOnResource(resources = "classpath:mysql.properties")
  6. @ConditionalOnWebApplication and @ConditionalOnNotWebApplication 
  7. @ConditionalExpression > @ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}")
  8. @Conditional > @Conditional(HibernateCondition.class)

This ensures that auto-configuration only applies when relevant classes, bean or properties are found and when you have not declared your own @Configuration
Will request you to go through previous post of Spring Boot to understand it in more detail.


Comments

Popular posts from this blog

Bubble sort Implementation

Bubble sort  : In bubble sort ,we will select the 1st element and compare with all the remaining element, same process we will continue for all the elements as we are traveling the whole Array 2 times except the element which we have selected to compare with other elements but still it will be consider as n time.    So time complexity for bubble sort will be O(n^2).         space complexity for bubble sort will be O(1). // Bubble Sort class BubbleSort { public static void sort ( int [] array) { int n = array. length ; while ( true ) { boolean swapped = false; for ( int i = 0 ; i < n - 1 ; i++) { if (array[i + 1 ] < array[i]) { swap (array , i , i + 1 ) ; swapped = true; } } if (!swapped) break; } } private static void swap ( int [] array , int i , int j) { int temp = array[i] ;...

Object-Oriented Programming Concept in Java

OOPS( Object-Oriented Programming ) Concept in Java :   As we all know Java is Object Oriented programming language and what exactly it means in simple words to understand can be described as whatever is going to happen by Java , it will be based on some Object.  So next question can be what is Object ? , "Object is the representation or reference of Class to access its properties and use its behaviour ", now next is What is Class in java and answer to this question is "A class in java is the blueprint of Properties and Behaviours of it's own Object" as explained in my previous post  BASIC OVERVIEW OF JAVA  (SESSION 1)   Let's understand through an example : public class FirstJavaProgram { int firstNumber=10; int secondNumber=20;      public int sum(int fNum, int sNum){         return fNum+sNum;     }     public static void main(String[] args) {     //our logics ...

JAVA MEMORY LEAK, UTILISATION AND MONITORING USING JFR using Mission Control

JAVA MEMORY LEAK, UTILISATION AND MONITORING USING JFR using Mission Control Java flight recording(JFR) help us to analyse and find the root cause of any slowness in our program along with CPU usage , hot methods and garbage collection , profiling etc. To visualise we need to feed .jfr file to JDK mission control present in JDK bin folder. After successful compilation , we should run the program with below option which will generate the .jfr and feed to mission control.   command :  j ava -XX:+UnlockCommercialFeatures -XX:+FlightRecorder  -XX:StartFlightRecording=duration=200s,filename=flight.jfr -cp ./out/ path-and-class-name Below are some example to understand how this JFR can be helpful. 1. Lets consider we have created a java program in which we have used LinkList to store the elements and in same program we are using contains method inside a for loop of 1 million , in this case each time this contains method will be called then 1 million records will be sc...