Spring in General
Spring in General
Spring Module 2
Spring Boot 9
Feature 9
Key Components of Spring Boot Framework 10
What is Spring Boot Actuator? 10
What is Spring Boot Initializr? 10
How to reload Spring Boot Application without restarting server? 11
Spring Rest 11
What are Safe Operation? 11
What are idempotent Operation? 11
Spring Data 11
Benefits of Spring Framework
Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of
spring framework is around 2MB.
Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control
technique. The objects give their dependencies instead of creating or looking for dependent
objects.
Aspect oriented (AOP): Spring supports Aspect oriented programming and separates
application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application objects.
MVC Framework: Spring’s web framework is a well-designed web MVC framework, which
provides a great alternative to web frameworks.
Transaction Management: Spring provides a consistent transaction management interface that
can scale down to a local transaction and scale up to global transactions (JTA).
Exception Handling: Spring provides a convenient API to translate technology-specific
exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.
Spring Module
core Module -
> The Core and Beans modules provide the most fundamental parts of the framework
and provides the IoC and Dependency Injection features.
> The Context module inherits its features from the Beans module and adds support for
internationalization (I18N) (using for example resource bundles), event-propagation,
resource-loading, and the transparent creation of contexts by, for example, a servlet
container. The Context module also contains support for some Java EE features like
EJB, JMX and basic remoting support. The ApplicationContext interface is the focal point
of the Context module that provides these features.
> The Expression Language module provides support to setting and getting property
values, method invocation, accessing collections and indexers, named variables, logical
and arithmetic operators, retrieval of objects by name etc.
ORM Module - spring data JPA and hibernate
Web Module - spring MVC
Security Module - Authentication and Authorization
Spring AOP -aspect-oriented programming implementation allowing you to define, for example,
method-interceptors and pointcuts to cleanly decouple code implementing functionality
Spring Test - Test module contains the Test Framework that supports testing Spring
components using JUnit or TestNG. It also contains a number of Mock objects that are useful in
many testing scenarios to test your code in isolation.
The @Bean annotation returns an object that spring should register as bean in application
context. The body of the method bears the logic responsible for creating the instance.
Type of DI are :
1. Constructor Based
2. Setter Based
3. Field Based
Constructor Based
Setter Based
Constructor-based and setter-based types of injection can be combined for the same bean. The
Spring documentation recommends using constructor-based injection for mandatory
dependencies, and setter-based injection for optional ones.
Field Based
In case of Field-Based DI, we can inject the dependencies by marking them with an
@Autowired annotation:
While constructing the Store object, if there’s no constructor or setter method to inject the Item
bean, the container will use reflection to inject Item into Store.
public class Store {
@Autowired
private Item item;
}
.
This approach might look simpler and cleaner but is not recommended to use because it has a
few drawbacks such as:
- This method uses reflection to inject the dependencies, which is costlier than
constructor-based or setter-based injection
Note- Java Reflection makes it possible to inspect classes, interfaces, fields and
methods at runtime, without knowing the names of the classes, methods etc. at
compile time. It is also possible to instantiate new objects, invoke methods and
get/set field values using reflection.
- It’s really easy to keep adding multiple dependencies using this approach. If you were
using constructor injection having multiple arguments would have made us think that the
class does more than one thing which can violate the Single Responsibility Principle.
More
If there’s more than one bean of the same type, we can use the @Qualifier annotation to
reference a bean by name:
@Autowired
private Item item;
@Autowired
@Qualifier("item1")
private Item item;
}
@Configuration
public class AppConfig {
@Bean
public Item item1() {
return new ItemImpl1();
}
@Bean
public Store store() {
return new Store(item1());
}
}
The Controller takes the request and calls the appropriate service methods based on used GET
or POST method. The service method will set model data based on defined business logic and
returns view name to the DispatcherServlet.
The DispatcherServlet will take help from ViewResolver to pick up the defined view for the
request.
Once view is finalized, The DispatcherServlet passes the model data to the view which is finally
rendered on the browser.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:*-context.xml</param-value>
</context-param>
In the above configuration, I am asking spring to load all files from the classpath that match
*-context.xml and create an Application Context from it. This context might, for instance, contain
data access objects, or other objects that you might want to use (and re-use) across the
application. This context can be used to load and unload the spring-managed beans irrespective
of what technology is being used.
The other context is the "WebApplicationContext" which is the child context of the application
context. Each DispatcherServlet defined in a Spring web application will have an
associated WebApplicationContext. The initialization of the WebApplicationContext happens
like this:
<servlet>
<servlet-name>platform-services</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</ser
vlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:platform-services-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
DispatcherServlet
In Spring MVC all incoming requests go through a single servlet. This servlet
- DispatcherServlet- is the front controller. Front controller is a typical design pattern in the web
applications development. In this case, a single servlet receives all requests and transfers them
to all other components of the application.
The task of the DispatcherServlet is send request to the specific Spring MVC controller.
Usually we have a lot of controllers and DispatcherServlet refers to one of the following
components to determine the target controller:
● BeanNameUrlHandlerMapping;
● ControllerBeanNameHandlerMapping;
● ControllerClassNameHandlerMapping;
● DefaultAnnotationHandlerMapping;
● SimpleUrlHandlerMapping.
If do not configure the others,
the DispatcherServlet uses BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMappi
ng.
When the target controller is defined, the DispatcherServlet sends request to it. The controller
performs some work according to the request (or delegate it to the other objects), and returns
back to the DispatcherServlet the Model and the name of the View.
The name of the View - it is only the logical name. This logical name then used to search for the
actual View (to avoid coupling with the controller and specific View).
Then DispatcherServletrefers to the ViewResolver and maps the logical name of the View to the
specific implementation of the View.
Implementations of the ViewResolver:
● BeanNameViewResolver;
● ContentNegotiatingViewResolver;
● FreeMarkerViewResolver;
● InternalResourceViewResolver;
● JasperReportsViewResolver;
● ResourceBundleViewResolver;
● TilesViewResolver;
● UrlBasedViewResolver;
● VelocityLayoutViewResolver;
● VelocityViewResolver;
● XmlViewResolver;
● XsltViewResolver.
When the DispatcherServlet determines the view that will display the results (model), this view
will render to the response.
Finally, the DispatcherServlet returns the Response object back to the client.
It’s a framework for building and running Spring Application. Basically, in gone days, biggest
challenge faced by developer was the amount of time they spent on configuration and running
application. So, with growing number of framework in spring community, it was necessary to
have a framework to solve the configuration. Spring boot simply scan the class path and
required libraries from various repositories. This improves productivity and save lots of
developer time.
Feature
● Create stand-alone Spring applications
● Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
● Provide opinionated 'starter' POMs to simplify your Maven configuration
● Automatically configure Spring whenever possible
● Provide production-ready features such as metrics, health checks and externalized
configuration
● Absolutely no code generation and n o requirement for XML configuration
Spring Boot AutoConfigurator: One of the common complaint with Spring is, we need to
make lot of XML based configurations. Spring Boot AutoConfigurator will simplify all these XML
based configurations. It also reduces the number of annotations.
Spring Boot CLI: Spring Boot CLI(Command Line Interface) is a Spring Boot software to run
and test Spring Boot applications from command prompt.
Here are some of the most common Spring Boot Actuator endpoints:
Http Operation ‘GET’ and ‘HEAD’ are safe operation as it doesn’t modify the resource at server.
Whereas POST, PUT, DELETE are unsafe as they modify the resource on the server.
Sending multiple GET request to same URI result same response hence it is idempotent. On
the other hand POST is not idempotent as if we send multiple POST request on server, it will
result multiple resource creation on the server .
Note: multiple PUT request to update resource on a server will give same end result so in that
scenario PUT is idempotent
Spring Data
Spring Data provides Abstractions (interfaces) you can use irrespective of underlying data
source.