0% found this document useful (0 votes)
66 views

Spring in General

The document provides an overview of key concepts in the Spring framework, including bean scopes, modules, IOC containers, annotations like @Component and @Bean, lazy initialization, dependency injection, Spring MVC architecture, and differences between Spring MVC and RESTful web services. It also covers Spring Boot features, components, and reload capabilities as well as Spring Data and REST concepts like safe and idempotent operations.

Uploaded by

Dipen Dahal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Spring in General

The document provides an overview of key concepts in the Spring framework, including bean scopes, modules, IOC containers, annotations like @Component and @Bean, lazy initialization, dependency injection, Spring MVC architecture, and differences between Spring MVC and RESTful web services. It also covers Spring Boot features, components, and reload capabilities as well as Spring Data and REST concepts like safe and idempotent operations.

Uploaded by

Dipen Dahal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Benefits of Spring Framework 2

Spring Bean Scope 2

Spring Module 2

Spring IOC Container 3


Two types of IoC containers 3

Difference between @Component and @Bean 4

When to you @Bean 4

Difference between @Component, @Service, @Repository and @Controller annotations 4

Lazy Initialized Beans 5

Dependency Injection in Spring 5

Spring MVC Architecture 6


Application Context and Web Application Context 7
DispatcherServlet 8

Difference between Spring MVC and RESTful web services 9

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 Bean Scope


singleton: Return a single bean instance per Spring IOC container.
prototype: Return a new bean instance each time when requested.
request: Return a single bean instance per HTTP request.
session: Return a single bean instance per HTTP session.
global session: Return a single bean instance per global HTTP session.

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.

Spring IOC Container


IoC is when you have someone else create objects for you.” So instead of writing “new
MyObject” in your code, the object is created by someone else. This ‘someone else’ is normally
referred to as an IoC container.
It is a process whereby objects define their dependencies.The container then injects those
dependencies when it creates the bean.
The IoC container is responsible to instantiate, configure and assemble the objects.The main
tasks performed by IoC container are:
- To instantiate the application class.
- To configure the object.
- To assemble the dependencies between the objects.

Two types of IoC containers


1. BeanFactory
BeanFactory is the basic container providing the basic support for DI (dependency
injection) and is defined by the org.springframework.beans.factory.BeanFactory
interface.
2. ApplicationContext
ApplicationContext is the advanced container and is defined by the
org.springframework.context.ApplicationContext interface

The ApplicationContext container includes all the functionality of the BeanFactorycontainer, so it


is generally recommended over BeanFactory as it provide more facilities than BeanFactory such
as integration with spring AOP, message resource handling.
Difference between @Component and @Bean
@Component and @Bean do two quite different things
The difference is that @Bean is applicable to methods, whereas @Component is applicable to
types.Therefore when you use @Bean annotation you control instance creation logic in
method's body. With @Component annotation you cannot.
@Component (and @Service and @Repository) are used to auto-detect and auto-configure
beans using classpath scanning.
@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically
as above. It decouples the declaration of the bean from the class definition, and lets you create
and configure beans exactly how you choose

When to you @Bean


Sometimes automatic configuration is not an option. When? Let's imagine that you want to wire
components from 3rd-party libraries (you don't have the source code so you can't annotate its
classes with @Component), so automatic configuration is not possible.

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.

Difference between @Component, @Service,


@Repository and @Controller annotations
Technically, there is no difference between them with respect to bean creation and dependency
injection
but every annotation should be used for a special purpose and with in the defined layer. Here is
the purpose of each annotation
@Component: ​is a generic stereotype for any Spring-managed component or bean
@Repository:​ is a stereotype for persistence layer
@Service: is a stereotype for the service layer and indicates annotated class is a Service
component in the business layer.
@Controller: indicates that it is a controller components, and mainly used at presentation
layer.DispatcherServlet will look for @RequestMapping on classes which are annotated using
@Controller.Even if you replace @Controller annotation with @Compoenent, Spring can
automatically detect and register the controller class but it may not work as you expect with
respect to request mapping
Difference between @Configuration and
@Component
In @Configuration classes, methods are annotated with @Bean which return object of the class.
It means class annotated with this annotation is the place where beans are configured.
@Componet class are candidates for autowiring on another class.

Lazy Initialized Beans


By default, the container creates and configures all singleton beans during initialization. To
avoid this, you can use the lazy-init attribute with value true on the bean configuration:

<bean​ ​id="item"​ ​class="org.store.ItemImpl"​ ​lazy-init="true"​ ​/>


As a consequence, the item bean will be initialized only when it’s first requested, and not at
startup. The advantage of this is faster initialization time, but the trade-off is that configuration
errors may be discovered only after the bean is requested, which could be several hours or
even days after the application has already been running

Dependency Injection in Spring


Dependency Injection is a software design pattern that allows us to develop loosely coupled
code.
In Spring, DI is fundamental aspect through which the spring container injects objects into other
objects as dependencies. This allows for loose coupling of components and moves the
responsibility of managing components onto the container.

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:

public class Store {

@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());
}
}

Spring MVC Architecture


In Spring MVC DispatcherServlet act as a Front Controller for the framework and responsible for
intercepting every request and then dispatches/forwards request to appropriate controller. After
receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the
appropriate Controller.

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.

Application Context and Web Application Context


In Spring Web Applications, there are two types of containers, each of which is configured and
initialized differently. One is the "Application Context" and the other is the "Web Application
Context"

Application Context is the container initialized by


a ​ContextLoaderListener​ or ​ContextLoaderServlet​ defined in the ​web.xml​ and the
configuration would look something like this:

<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​ creates its own ​WebApplicationContext​ and the


handlers/controllers/view-resolvers are managed by this context

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 ​DispatcherServlet​refers 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.

Difference between Spring MVC and RESTful web


services
The key difference between a Spring MVC controller and the RESTful web service controller is
the way the HTTP response body is created. While the MVC controller relies on the View
technology, the RESTful web service controller simply returns the object and the object data is
written directly to the HTTP response as JSON/XML
Spring Boot
Spring Boot providing you the shortest way to have a Spring web application up and running
with smallest line of code/configuration out-of-the-box.

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

Key Components of Spring Boot Framework


Spring Boot Starters: The main responsibility of Spring Boot Starter is to combine a group of
common or related dependencies into single dependencies. Examples are
spring-boot-starter-web, spring-boot-starter-test, spring-boot-starter-data-jpa, etc.

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.

Spring Boot Actuator:


What is Spring Boot Actuator?
Spring Boot Actuator is a sub-project of Spring Boot.The Spring Boot Actuator is mainly used to
get the internals of running application like health, metrics, info, dump, environment, etc.

Here are some of the most common Spring Boot Actuator endpoints:

/health​: It shows application health information.


/info​: It displays arbitrary application info.
/metrics​: It gives all metrics related information for the current application.
/trace​: It displays trace information for last few HTTP requests.

What is Spring Boot Initializr?


The Spring Initializr is ultimately a web application that can generate a Spring Boot project
structure for you. It doesn’t generate any application code, but it will give you a basic project
structure.
Spring Initializr can be used several ways, including:
● A web-based interface.
● Via IDE like intelliJ, STS

How to reload Spring Boot Application without restarting server?


During our development time, we need to restart the server to reflect our changes. But with the
introduction of spring-boot-devtools with Spring Boot application, we don't need to restart our
server.
Spring Rest
What are Safe Operation?

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.

What are idempotent Operation?

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.

You might also like