Thursday, December 15, 2016

Learn Java Spring in 20 minutes

       Client Server Architecture

       To start we must understand client server architecture, which can be seen in below diagram-:
           MVC Architecture
One of the earliest architecture which standardized procedures in client server architecture is MVC architecture.



       Struts
For the ease of developer, frameworks were introduced based on MVC architecture at its core. Struts with different version was introduced.




       Why Use Spring?
Spring having this much of demand because of the following 3 reasons….
  • Simplicity
  • Testability
  • Loose Coupling
The Spring framework is an extremely powerful Inversion of control(IoC) framework to help decouple your project components’ dependencies.

       Spring Introduction

Spring is a light weight (because of its POJO model)and open source framework.
Spring framework can be used for all layer implementations for a real time application or spring can be used for the development of particular layer of a real time application unlike struts [ only for front end related ] and hibernate [ only for database related ], but with spring we can develop all layers.

       Spring Modules


       Inversion of Control

The IOC container is responsible to instantiate, configure and assemble the objects. The IOC container gets information from the XML file and works accordingly. The main tasks performed by IOC container are:
  • to instantiate the application class
  • to configure the object
  • to assemble the dependencies between the objects.

There are two types of IOC containers. They are:
  • BeanFactory
  • ApplicationContext

Spring IOC container takes a form of configuration metadata(Which explain container how to initiate
object and configure) and combine it with application classes which in the end produces fully configured system.

Configuration metadata required for container can be provided in any of three ways.
  • XML
  • Java Code
  • Java Annotations

       Spring Core Example
     







    Dependency Injection

Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled.

Spring framework provides two ways to inject dependency
  • By Constructor
  • By Setter method

     Constructor based dependency Injection


       Setter based Dependency Injection


 Difference between Setter and Constructor based Dependency

  • Setter Injection is more readable than constructor injection in Spring configuration file usually applicationContext.xml . 
  • Another difference between setter vs constructor injection in Spring and one of the drawback of  setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.
  •  One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call the constructor, a new object is gets created.
  • Also drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using "dependency-check" attribute of  tag or tag.
  • Setter Injection is preferred choice when number of dependency to be injected is lot more than normal, 




       Bean Definition


       Bean scope
  
Example of Singleton-:






   Example of Prototype-:


Autowiring in Spring

The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration you write for a big Spring based application.



Example of code with/without using autowiring


Example of byType-: If a bean definition is set to autowire byType in configuration file, and it contains a spellChecker property of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the property. Still you can wire remaining properties using <property> tags.

Bean Life Cycle

There are various interfaces that bean class can implement and can get method to control bean lifecycle at various stage.
  1. Instantiate - The Spring container instantiates the bean.
  2. Populate properties- Spring IoC container injects the bean’s properties.
  3. Set Bean Name- Spring container sets the bean name. If the bean implements BeanNameAware, spring container passes the bean’s id to setBeanName() method.
  4. Set Bean Factory-If the bean implements BeanFactoryAware, Spring container passes theBeanFactory to setBeanFactory().
  5. Pre Initialization-This stage is also called the bean postprocess . If there are anyBeanPostProcessors, theSpring container calls the postProcesserBeforeInitialization () method.
  6. Initialize beans- If the bean implements IntializingBean,its afterPropertySet()method is called. If the bean has init method declaration, the specified initialization method is called.
  7. Post Initialization- IfBeanPostProcessors is implemented by the bean, the Spring container calls their postProcessAfterinitalization() method.
  8. Ready to Use- Now the bean is ready to be used by the application.
  9. Destroy- The bean is destroyed during this stage. If the bean implements DisposableBean, the Spring IoC container will call the destroy() method . If a custom destroy () method is defined, the container calls the specified method.


Spring MVC

Spring MVC provides an elegant solution to use MVC in spring framework by the help of DispatcherServlet.

In Spring Web MVC, DispatcherServlet class works as the front controller. It is responsible to manage the flow of the spring MVC application.

There are basically 4 annotations , most commonly used, @Component,@Controller(used for controller part),@Service(used for business layer),@Repositories(used for DAO layer). Last three are layer specific whereas Component is generic.

The @Controller annotation is used to mark the class as the controller in Spring 3.The @RequestMapping annotation is used to map the request url. It is applied on the method and used in conjunction with @controller.

Upon initialization of DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory.


Architecture



MVC Example


controller








Spring Event handling 


S.N.Spring Built-in Events & Description
1
ContextRefreshedEvent
This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
2
ContextStartedEvent
This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event.
3
ContextStoppedEvent
This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event.
4
ContextClosedEvent
This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
5
RequestHandledEvent
This is a web-specific event telling all beans that an HTTP request has been serviced.

Follow link for https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html  

No comments:

Post a Comment

Interview Prep: Java full stack

 SOLID principle :  https://www.educative.io/answers/what-are-the-solid-principles-in-java Design Pattern:  Creational:  https://medium.com...