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

Java Program : Writing First Java Factorial Program with explanation

 NAMING CONVENTION IN JAVA : Java is an object oriented programming language , we can relate it to real life object like i mapped Java with human in my previous post JAVA OVERVIEW (SESSION 1)  and represent human properties like body parts as properties in Java and Human can dance , drive , walk , run these can be mapped as Behaviour in java.    Now To represent properties and behaviour in java , there are some standard naming conventions we should follow. Class name should always starts with Uppercase letter like class Student { //Code to be executed } Properties or any kind of variables should starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ; //Code to be executed } Methods name should also starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ;

OOPS Concept in Java : ENCAPSULATION

OOPS Concept in Java : ENCAPSULATION   This OOPS concept can be used to make things simpler in case of software development . Main purpose of this concept is to hide the properties of any class and give access to fetch and modified based on business criteria.  A simple example can be a POJO ( Plain Old Java Object) in which all the properties of a class can be private and through getter and setter method of properties we can fetch and update the properties of Object. So instead of having direct access to properties we have created 2 methods to make the CLASS things encapsulated in single unit while access to it is via 2 public methods.   Just consider we have requirement that once the object is created its value should not be changed then simplest way to achieve this  can be done by just removing setter method and we will keep only getter methods to access Object properties . In this case after Object creation whatever the value of Object properties has been initialised it will b

OOPS Concept in Java : POLYMORPHISM

 POLYMORPHISM IN JAVA :  Polymorphism means mutiple forms of Single reference. And to understand in simple way just take an example from my previous post of OOPS CONCEPT IN JAVA : INHERITANCE  , I request you guys to go through this link before proceding here. So in this post I have created a method called sum() in PARENT class which has been used by CHILD class without writing same sum() method in CHILD class. This was possible becuase of INHERITANCE concept in java.  But what if CHILD class is not satisfied with PARENT sum() and CHILD class wants to improve it like by adding some message before the calculation. To do this we have another OOPS CONCEPT IN JAVA i.e POLYMORPHISM and by applying this logic we can make same sum() method behvae differently based on Object. As I mentioned earlier POLYMORPHISM means different forms and same has been achieved here by calling same sum() method but the output is different based on Object on which it has been called. If Object is of PARENT