Spring Core

Spring Framework
  • Spring framework is a dependency injection framework to make Java applications loosely coupled.
  • Spring framework makes the development of Java EE application easy.
  • Spring was developed by Rod Johnson in 2003.
  • Quickly build java enterprise application.
  • Provides a template for common services like Transaction Management and Garbage Collection
  • Developers only focus on writing business logic.
  • Framework takes care of other concerns like DB Connectivity.
Disadvantages
  • Build and Deployment effort is high with a Spring Framework Application as we need to configure a lot of things to make it work the way we like.
Dependency Injection
  • When we use New keyword, to inject our object, our code will become tightly coupled.
  • When we use dependency injection to add dependency in our, code remains loosely Coupled.
  • This is also called as inversion of control since spring will create an object of class and Will inject to another class. So the responsibility of injecting dependencies lies with spring and not the application.
Spring Core Modules
  • Spring Core
    • Spring Core and Spring Beans are Fundamental parts Of framework which provide features like IOC and dependency injection.
  • Spring beans
  • Spring context
    • Spring context inherits features from bean module and adds Features like internationalisation, event propagation, resource loading and Transparent creation of context.
      • Provides Java EE features like EJB, JMS and basic remoting.
  • spEL or Spring expression language is a powerful tool to query expression, language and manipulate the object graph at runtime.
Spring AOP Modules
  • Spring AOP
    • Helps us to define method interceptors and point cuts to cleanly decouple a code.
  • Spring instrumentation
  • Spring Aspect
  • Spring Messaging
    • Messaging To serve messaging concept. Among methods, we can map messages to methods and communicate.
Spring Web Module
  • Web
    • Web oriented integration feature is provided by web modules
      • File uploading on server
      • Rest API’s
  • Servlet
  • Portlet
    • Portlet based Applications can be created using this.
  • Websocket
Spring Test Module
  • Unit testing
  • Integration testing
  • Provides mock objects for mockito/isolation based testing.
Spring Data Access and Integration Tools
  • JDBC
    • Enhances old JDBC.
  • JMS
    • JMS is used to produce and consume messages.
  • ORM
    • Like hibernate provides Integration layer for ORM tools.
  • OXM(Object XML Mapping)
    • For tools like coster, xstream
Spring IOC Container
  • Used for creating and holding objects in memory.
  • Use for injecting one object in another object.
  • Maintain the life cycle of an object.
  • We need to define, define the object/class to be maintained by this container has Bean.
    • We must provide a configuration file which defines beansand their dependency.
  • It creates and initialises the objects at the time application is built.
  • We must not define third-party services such as cloud services as Beans because our build tool might not have permission to access the services.
    • These permissions are only available with container in which our jar runs.
  • Application context acts as an interface to access IOC container.
    • Application context extends bean factory. Its subclasses are.
      • Classpath XML application context.
        • Searches for XML configuration IN Java classpath.
      • Annotation config Application context.
        • Searches for Bean in the annotation we have used.
        • Searches for beans defined using annotation.
      • File system XML Application, context.
        • Searches for config file in file system.
  • Dependency injection can be done in two ways
    • Using Setter injection
      • Uses setter method To set values.
      • Also known as property injection.
    • Using constructor injection
      • Uses constructor to set values.
      • We use all argument constructor.
  • We define all these settings in configuration file which is a XML file.
    • We declare beans and its dependency.
    • We use beans tag with a child bean tag in it to define beans.
  • Data types that can be injected by dependency injection
    • Primitive data type
      • Byte, Short, Char, Int, Float, Double, Long, Boolean.
    • Collection data type
      • List, Set, Map and properties.
    • Reference data type
      • Other class objects.
Spring MVC Framework
  • Spring MVC is a Java Model View Controller architecture framework.
  • It is a web framework for Spring applications.
  • It is a perspective of changing approach to Web Development.
  • Spring MVC have developed a framework that helps us structure our web applications.
  • This framework is built on top of Spring which helps components in our framework to be flexible and loosely coupled.
  • Framework adheres to separation of concerns principal and divides different layers of the web application accordingly.
  • Custom based java applications which used jsp's and servlet's had all their code contained in JSP files as such there was no consistency or architecture to these applications.
  • The logic and authentication code went into the jsp's.
  • Flexibility to reuse different components and different layers within our application.
  • Built on Spring IOC container
    • Spring IOC allows us to perform dependency injection.
  • Integrates very well with other Spring projects.
    • Spring Data
    • Spring hibernate integration
    • Spring Security
  •   These can be easily integrated in our Spring MVC project.
  • Spring data and Spring security are most commonly used with Spring MVC.
Spring MVC configuration
  • Different beans allows us to customize different pieces of the framework and make them perform in different manners.
Spring Boot
  • Using Spring Boot we can bootstrap or quickly start a Spring Application.The application is pre configured.
  • Spring Boot is an opinionated framework i.e. most of the features and functionalities for non functional requirements are already given and we can customize it in our application to taste.
  • Types of application built using Spring Framework is
    • Website
    • Webservice/Rest Service
    • Backend Batch Process.
  • Spring Boot comes with embedded tomcat server.
  • We can download a configured spring boot application from "start.spring.io".
Key Framework Components
  • Controllers
  • View Resolvers
  • Views
  • Handler interceptors
  • Request mapping
  • Data Binding
Request Processing Lifecycle
  • Taking in request from user and sending back response
  • Spring MVC delivers components that are ready for our use that are able to do things such as data bindings, or resolving our views etc.
  • There are many other components that handle the bulk of request processing in Spring MVC framework.
Preferred IDE's
  • The preferred IDE to develop Spring Applications is Spring Tool Suite.
    • This is an eclipse based IDE enhanced to support development with Spring projects.
  • However we can even use Eclipse,Netbeans,Aptana,Visual Studio to develop such applications.
  • I will be using Spring Tool Suite(STS) initially.However I will also test my app on Netbeans and Eclipse and Visual Studio if possible.
  • Aptana is again an extension of Eclipse. 
Prerequisites
  • Java(servlet API)
  • Spring Core
  • HTML,Javascript,XML
  • Maven(installation)
  • Java system variables are set
  • Maven system variables are set
Model View Controller
  • Provides basic architecture of spring mvc framework.
  • It is a software development pattern, principle or architecture that separates 3 primary principle concerns:
    • Model
      • Objects representing application data
      • Example customers and orders so each object will store related Application data.
      • May also be some custom object to support our application.
      • Example of Model
        • Wrapper class for Table User with following attributes
          • id int
          • first_name varchar(45)
          • last_name varchar(45)
          • birth_date Date
      • A model may be a replica of a Database table or a middle layer between controller and Application Data.
    • View
      • Visual user interface that renders the model.
      • User interfaces that are a part of our application.
      • Information from model is displayed in view.
      • Example of View
        • A web form with all the fields of User above as input fields.
      • View collects information from controller.
      • We can even change our view without having to change our controller or model.
    • Controller
      • Preforms application logic,facilitates model and view interactions.
      • Acts as a mediator between model and view
      • Contains all that actions that we can perform within our application.
      • For example when we send some data via request to be saved controller saves the data.
      • Example of controller
        • User user=getUserFromView();
        • updateUserProfile(user);
        • castVote(user);
      • Controller conducts interaction between model and view
        • Gets user from view
        • Updates User profile in Model
        • Casts vote and saves it as an application data.
      • We can even call our controller from a web service which is another type of view.
Origin of MVC
  • MVC was basically for non web applications.
  • View,Model and Controller were intermingled in code and that was a big challange during maintenance.
  • Scripts used to be written directly in JSP files which was a big problem.
  • All the logic was placed in view from DB connections to Business Logic.As such the code became spaghetti code thus harder to maintain.
Application of MVC
  • Request is sent to a server hosts MVC application via browser
  • Requested is routed via MVC and response is returned back to the browser.
Benefits of MVC
  • Code becomes reusable.
  • Reduces coupling withing our application and reduces dependencies among our components.
  • The components can be used independently.
  • An object of a model can be used across multiple views or in multiple controllers because it does not have business logic embedded into it or view information in it.
  • Same model can be used for HTML and json outputs.
  • Provides architecture for a web application.
Request Processing Lifecycle

  • Receives request and returns responses
  • Uses front controller pattern
    • Front controller receives request from the web browser or a web service.
    • Front controller is the single point of entry.
    • Front controller analyzes a url and maps the same to a particular controller.
    • Once the controller is found that is assigned to particular url processing is then forwarded to the controller.
    • Controller applies business logic and builds a model.
    • Model holds all the different objects that hold data for our system.
    • Controller returns the model and view that needs to be rendered.
      • Controller sends view and model back to front controller.
    • Front Controller locates view and passes it the model
    • The view is rendered and returned to front controller and then it is returned as response to the browser.
  • While developing an application without an MVC framework we use a servlet and the servlet has its own custom framework building.
    • Multiple servlets in such a case may use multiple approaches.
    • All of this work is oftenly done in jsp which disorganizes the code.
  • We can customize this lifecycle at different points eg.
      • Manipulate model
      • Change approach how the front controller determines which controller is selected to handle particular url.
      • Customize view selection.
      • Customize data binding.
Data Binding
  • When a request is sent to server we have some request parameters that are sent along.
  • Spring MVC takes these parameters as key value pairs and locate a corresponding Model class which has same parameters and directly insert data to the Model class.
  • Spring also provides type conversion automatically for fields if needed.
  • In past we manually needed to get request parameters and check if the value for corresponding model class variable was available.If it was we manually used to insert the same in our model class by assigning value to every field in the model class.
  • Spring performs all this data binding automatically for us by mapping request to model.
  • We can customise this data binding to handle lists,collections,arrays.
Spring Standard Collections
  • We will use util schema to create spring Stand alone Collection as follows.
    •  <beans   
       xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:context="http://www.springframework.org/schema/context"  
       xmlns:p="http://www.springframework.org/schema/p"  
       xmlns:c="http://www.springframework.org/schema/c"  
       xmlns:util="http://www.springframework.org/schema/util"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans.xsd  
       http://www.springframework.org/schema/context  
       http://www.springframework.org/schema/context/spring-context.xsd  
       http://www.springframework.org/schema/util  
       http://www.springframework.org/schema/util/spring-util.xsd">  
      
  • When we insert property of type list by default, array list type is inserted Insert link list, we need to define a standalone collection.
Autowiring in spring
  • Feature of Spring framework in which spring container inject the dependence automatically.
  • Autowiring Can’t be used to inject Primitive and string values.It works with reference types only that is only with object.
  • In Autowiring Spring container Automatically links 2 objects.
  • Autowiring can be done in following ways
    • XML
      • Done using Autowiring modes.
        • No mode Where an empty bean tag means it shouldn’t be Autowired.
      • Done using name
        • Using bean name We can search for dependencies.
      • Done using type
        • Using Bean type We can search for dependencies.
      • Constructor
        • Can be done by calling concerned constructor.
      • Autodetect
        • Deprecated since spring 3.
    • Annotations
      • Use @Autowired annotation
      • Use @Qualifiers annotation
      • Use @Values annotation.
  • Annotation based Autowiring
    • We use @Autowired annotation, we can add on setter injection, Property or constructor.
    • To Enable @Autowired Annotation add following tag in your beans xml for java 9 and above.
      •  <!-- Enables all Annotations of Java EE-->  
         <context:annotation-config />  
         <!-- Enables all Annotations of Java EE-->  
         <!-- To Enable Particular Annotaion create it's bean -->  
         <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>  
         <!-- To Enable Particular Annotaion create it's bean -->  
        
      • This tag is used to enable Java EE annotation which are disabled by default in Java 9 and above.
  • Advantages
    • Automatic dependency injection
    • Less code
  • Disadvantages
    • No control of programmer
    • It can’t be used for primitive and string values.
Stereotype Annotations
  • Used to tell spring Container about beans Using annotations.we use annotations like @component etc.
  • We need to define the package of our class which will be scanned for beans.
    • <context:component-scan base-package="" />
  • Creates beans With camel case, variables of class names.
Bean scopes in Spring
  • Different bean scopes are as follows.
    • Singleton
    • Prototype
    • Request
    • Session
    • Global Session
  • Singleton and prototype are used for core applications.
  • Request and session are used for web applications.
    • Request scope is available from HTTP request object.
    • Session scope is available from HTTP session object.
  • Global session is used for Portlet type of application.
    • Singleton creates only one object of a class.
    • Prototype Creates a new object each time a bean is called.
  • Bean scope Can be configured using XML or annotation
    • <bean class=“” scope=“”/>
    • @Scope

Filters vs Interceptors

  • Filter, modify the header of request and response.
  • Interceptor modifies the body of a request and response.
  • Example, client request filter and client response filter
    • Filter is a Java class, which is executed before a request reaches spring and before response, reaches client.
    • Used for authorisation and authentication
    • Used for logging
    • Addresses code duplication
    • Filter is a Web servlet, Container concept.
    • Order of filters
      • We can start using @order annotation.

Other Features
  • Error handling and validation
  • Validate user data in correspondence to model  object so that when data binding occurs we can have different validations in place and in case of error provide an error to user interface.
  • File upload support
    • Reduces the work load need to perform to upload a file.
  • Spring tag library
    • Has a tag library that helps us in data binding and tying our interface data from backend objects.
    • Helps to display multiple views back to user such as
      • excel
      • pdf
      • json
      • xml
  • Spring MVC facilitates the development of Java web applications
    • Contains all features for handling usecases in web application
  • Framework revolves around a dispatcher servlet that integrates with a Spring IOC container
    • Implements a front controller pattern.
    • Integrates with Spring IOC container
      • This allows us to use dependency injection.
    • We can autowire components directly.
  • Features such as databinding, view resolution and controllers support request processing.
    • We can customize request processing approach that Spring MVC takes using following
      • Request Mapping Annotation
      • Handler Interceptor
      • Controller Advice
      • Session Attributes
      • ResponseBody Annotation
Examples

No comments:

Post a Comment

Spring Boot

What is circular/cyclic dependency in spring boot? When two services are interdependent on each other, that is to start one service, we requ...