Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Spring Framework

Spring Framework

Spring is a lightweight framework. It can be thought of as a framework of


frameworks because it provides support to various frameworks such as Struts, Hibernate, etc.
The framework, in broader sense, can be defined as a structure where we find solution of the
various technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM,
WEB MVC etc. We will learn these modules in next page. Let's understand the IOC and
Dependency Injection first.

Inversion Of Control (IOC) and Dependency Injection

These are the design patterns that are used to remove dependency from the programming
code. They make the code easier to test and maintain. Let's understand this with the following
code:

1. class Employee{
2. Address address;
3. Employee(){
4. address=new Address();
5. }
6. }

In such case, there is dependency between the Employee and Address (tight coupling). In the
Inversion of Control scenario, we do this something like this:

1. class Employee{
2. Address address;
3. Employee(Address address){
4. this.address=address;
5. }
6. }

Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code
if our logic is moved to new environment.

In Spring framework, IOC container is responsible to inject the dependency. We provide


metadata to the IOC container either by XML file or annotation.

Advantage of Dependency Injection


o makes the code loosely coupled so easy to maintain
o makes the code easy to test

Advantages of Spring Framework

There are many advantages of Spring Framework. They are as follows:

1) Predefined Templates

Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is
no need to write too much code. It hides the basic steps of these technologies.

Let's take the example of JdbcTemplate, you don't need to write the code for exception
handling, creating connection, creating statement, committing transaction, closing connection
etc. You need to write the code of executing query only. Thus, it save a lot of JDBC code.

2) Loose Coupling

The Spring applications are loosely coupled because of dependency injection.

3) Easy to test

The Dependency Injection makes easier to test the application. The EJB or Struts application
require server to run the application but Spring framework doesn't require server.

4) Lightweight

Spring framework is lightweight because of its POJO implementation. The Spring


Framework doesn't force the programmer to inherit any class or implement any interface.
That is why it is said non-invasive.

5) Fast Development

The Dependency Injection feature of Spring Framework and it support to various frameworks
makes the easy development of JavaEE application.

6) Powerful abstraction

It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.

7) Declarative support

It provides declarative support for caching, validation, transactions and formatting.

Inversion of Control (IoC):

Imagine you are building a house. Normally, you would be responsible for everything – from
designing the architecture to arranging furniture. However, if you use IoC, you hire an
architect to design the house and a decorator to furnish it. You don’t have to worry about
these tasks; instead, you focus on enjoying your new home.

Spring Framework:

Spring applies IoC by managing the components of your application for you. Instead of your
code directly creating and managing objects (like how you would have to design and arrange
your house), Spring takes over this responsibility. It uses Dependency Injection (DI) to inject
necessary dependencies into your classes, reducing tight coupling and making your code
more flexible and easier to test and maintain.

What is AOP?

AOP allows you to add behavior to existing code without modifying it directly. This is useful
for cross-cutting concerns such as logging, security, transaction management, and caching,
which affect multiple parts of an application.

Key Concepts in AOP

1. Aspect: A module that encapsulates a concern that cuts across multiple classes.
2. Join Point: A point in the execution of the program, such as a method call or field
assignment.
3. Advice: The action taken by an aspect at a particular join point. Types of advice
include:
o Before: Executed before a method is called.
o After: Executed after a method has completed.
o Around: Surrounds a method call, allowing you to execute code before and
after the method.
o After Returning: Executed after a method returns a result.
o After Throwing: Executed if a method throws an exception.
4. Pointcut: A predicate that matches join points. Advice is associated with a pointcut
expression and runs at any join point matched by the pointcut.
5. Introduction: Adding methods or fields to existing classes.

How AOP Works in Spring

Spring AOP uses proxies to implement aspects. A proxy is an object that wraps the target
object and intercepts method calls to inject the advice code.

Example to Illustrate AOP

Suppose you want to add logging to the add method of a Calculator class.

1. Define the Business Logic

java
Copy code
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}

2. Define the Aspect

Use the @Aspect annotation to define an aspect.

java
Copy code
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;

@Aspect
public class LoggingAspect {

@Before("execution(* Calculator.add(..))")
public void logBefore() {
System.out.println("Before calling add method");
}

@After("execution(* Calculator.add(..))")
public void logAfter() {
System.out.println("After calling add method");
}
}

3. Configure Spring to Use AOP

You can configure AOP using XML or Java configuration.

XML Configuration:

xml
Copy code
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<bean id="calculator" class="Calculator"/>


<bean id="loggingAspect" class="LoggingAspect"/>

<aop:config>
<aop:aspect ref="loggingAspect">
<aop:pointcut expression="execution(* Calculator.add(..))"
id="addMethod"/>
<aop:before method="logBefore" pointcut-ref="addMethod"/>
<aop:after method="logAfter" pointcut-ref="addMethod"/>
</aop:aspect>
</aop:config>
</beans>

Java Configuration:
java
Copy code
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

@Bean
public Calculator calculator() {
return new Calculator();
}

@Bean
public LoggingAspect loggingAspect() {
return new LoggingAspect();
}
}

4. Enable AOP and Run the Application

java
Copy code
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
Calculator calculator = context.getBean(Calculator.class);
calculator.add(5, 3);
}
}

What is a Bean?

 Definition: A bean is a Java object that is instantiated, assembled, and managed by


the Spring IoC container.
 Configuration: Beans are typically configured in the Spring configuration file
(XML), annotated within Java classes, or defined in Java configuration classes.

Characteristics of a Bean

1. Instantiation: The Spring container is responsible for creating instances of beans.


2. Lifecycle Management: The Spring container manages the lifecycle of beans,
including their initialization and destruction.
3. Dependency Injection: The container also injects dependencies into the beans,
promoting loose coupling and easier testability.

Bean Scopes

In the Spring Framework, bean scopes define the lifecycle and visibility of beans. Each scope
specifies how and when a bean should be created, how long it should live, and how it should
be shared. Here are the main bean scopes in Spring:

1. Singleton Scope

 Definition: Only one instance of the bean is created per Spring IoC container.
 Lifecycle: The bean is created when the container is started and remains until the
container is shut down.
 Use Case: When a shared, stateful object is needed.
 Default Scope: If no scope is specified, the default scope is singleton.

Example:

java
Copy code
@Configuration
public class AppConfig {

@Bean
public MySingletonBean mySingletonBean() {
return new MySingletonBean();
}
}

2. Prototype Scope

 Definition: A new instance of the bean is created every time it is requested.


 Lifecycle: The bean is created and initialized when requested and then discarded after
use.
 Use Case: When a non-shared, stateful object is needed.
 Note: The Spring container does not manage the complete lifecycle of a prototype
bean (e.g., it does not call the destroy method).

Example:

java
Copy code
@Configuration
public class AppConfig {

@Bean
@Scope("prototype")
public MyPrototypeBean myPrototypeBean() {
return new MyPrototypeBean();
}
}

3. Request Scope (Web Context Only)

 Definition: A new instance of the bean is created for each HTTP request.
 Lifecycle: The bean is created and initialized at the beginning of an HTTP request and
destroyed at the end of the request.
 Use Case: For request-specific data in a web application.

Example:

java
Copy code
@Configuration
public class AppConfig {

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode =
ScopedProxyMode.TARGET_CLASS)
public MyRequestBean myRequestBean() {
return new MyRequestBean();
}
}

4. Session Scope (Web Context Only)

 Definition: A new instance of the bean is created for each HTTP session.
 Lifecycle: The bean is created and initialized at the beginning of an HTTP session and
destroyed when the session is invalidated or expires.
 Use Case: For session-specific data in a web application.

Example:

java
Copy code
@Configuration
public class AppConfig {

@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode =
ScopedProxyMode.TARGET_CLASS)
public MySessionBean mySessionBean() {
return new MySessionBean();
}
}

5. Application Scope (Web Context Only)

 Definition: A single instance of the bean is created per ServletContext.


 Lifecycle: The bean is created when the ServletContext is initialized and destroyed
when the ServletContext is destroyed.
 Use Case: For application-wide shared data.
Example:

java
Copy code
@Configuration
public class AppConfig {

@Bean
@Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode =
ScopedProxyMode.TARGET_CLASS)
public MyApplicationBean myApplicationBean() {
return new MyApplicationBean();
}
}

6. WebSocket Scope (Web Context Only)

 Definition: A single instance of the bean is created per WebSocket.


 Lifecycle: The bean is created at the start of the WebSocket session and destroyed
when the WebSocket session ends.
 Use Case: For WebSocket session-specific data.

Example:

java
Copy code
@Configuration
public class AppConfig {

@Bean
@Scope(value = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyWebSocketBean myWebSocketBean() {
return new MyWebSocketBean();
}
}

Summary

 Singleton: One instance per Spring IoC container (default).


 Prototype: A new instance for each request.
 Request: One instance per HTTP request (web apps).
 Session: One instance per HTTP session (web apps).
 Application: One instance per ServletContext (web apps).
 WebSocket: One instance per WebSocket session (web apps).

Autowiring in Spring

Autowiring is a feature in the Spring Framework that allows the Spring container to
automatically resolve and inject bean dependencies. Instead of explicitly defining the
dependencies in a configuration file, autowiring uses various strategies to automatically inject
the required dependencies into the beans.

Autowiring Modes
Spring provides several modes for autowiring:

1. no (default): No autowiring is done. You have to manually define the dependencies.


2. byName: Autowiring by property name. Spring looks for a bean with the same name
as the property to be autowired.
3. byType: Autowiring by property type. Spring looks for a bean of the same type as the
property to be autowired.
4. constructor: Autowiring by constructor. Spring looks for a constructor with
arguments that can be autowired by type.
5. autodetect: Spring first tries to autowire by constructor, and if that fails, it tries
byType.

Annotations for Autowiring

Spring provides several annotations to facilitate autowiring:

1. @Autowired

The @Autowired annotation is the most commonly used annotation for autowiring in Spring.
It can be applied to constructors, fields, and methods.

Example:

 Field Injection:

java
Copy code
@Component
public class MyService {
@Autowired
private MyRepository myRepository;
}

 Setter Injection:

java
Copy code
@Component
public class MyService {
private MyRepository myRepository;

@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}
}

 Constructor Injection:

java
Copy code
@Component
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
}

2. @Qualifier

The @Qualifier annotation is used in conjunction with @Autowired when there are multiple
beans of the same type and you need to specify which one should be injected.

Example:

java
Copy code
@Component
public class MyService {
@Autowired
@Qualifier("specificRepository")
private MyRepository myRepository;
}

3. @Primary

The @Primary annotation is used to give a higher preference to a bean when multiple beans
of the same type exist. If no @Qualifier is specified, the @Primary bean will be chosen.

Example:

java
Copy code
@Component
@Primary
public class PrimaryRepository implements MyRepository {
}

4. @Resource

The @Resource annotation is part of JSR-250 and is similar to @Autowired. It allows you to
specify a name for the bean to be injected.

Example:

java
Copy code
@Component
public class MyService {
@Resource(name = "myRepository")
private MyRepository myRepository;
}
Spring vs. Spring Boot
Spring: Spring Framework is the most popular application development framework
of Java. The main feature of the Spring Framework is dependency
Injection or Inversion of Control (IoC). With the help of Spring Framework, we can
develop a loosely coupled application. It is better to use if application type or
characteristics are purely defined.

Spring Boot: Spring Boot is a module of Spring Framework. It allows us to build a


stand-alone application with minimal or zero configurations. It is better to use if we
want to develop a simple Spring-based application or RESTful services.

The primary comparison between Spring and Spring Boot are discussed below:

Spring Spring Boot

Spring Framework is a widely used Spring Boot Framework is widely used to develop REST APIs.
Java EE framework for building
applications.

It aims to simplify Java EE development It aims to shorten the code length and provide the easiest way
that makes developers more to develop Web Applications.
productive.

The primary feature of the Spring The primary feature of Spring Boot is Autoconfiguration. It
Framework is dependency injection. automatically configures the classes based on the requirement.

It helps to make things simpler by It helps to create a stand-alone application with less
allowing us to develop loosely configuration.
coupled applications.

The developer writes a lot of code It reduces boilerplate code.


(boilerplate code) to do the minimal
task.

To test the Spring project, we need to Spring Boot offers embedded server such
set up the sever explicitly. as Jetty and Tomcat, etc.

It does not provide support for an in- It offers several plugins for working with an embedded and in-
memory database. memory database such as H2.

Developers manually define Spring Boot comes with the concept of starter in pom.xml file
dependencies for the Spring project that internally takes care of downloading the
in pom.xml. dependencies JARs based on Spring Boot Requirement.

o Now we have validator classes, view classes, and utility classes.


o Spring Boot uses all the modules of Spring-like Spring MVC, Spring Data, etc. The
architecture of Spring Boot is the same as the architecture of Spring MVC, except one
thing: there is no need for DAO and DAOImpl classes in Spring boot.
o Creates a data access layer and performs CRUD operation.
o The client makes the HTTP requests (PUT or GET).
o The request goes to the controller, and the controller maps that request and handles it.
After that, it calls the service logic if required.
o In the service layer, all the business logic performs. It performs the logic on the data
that is mapped to JPA with model classes.
o A JSP page is returned to the user if no error occurred.

Introduction to RESTful Web Services


REST stands for REpresentational State Transfer. It is developed by Roy Thomas
Fielding, who also developed HTTP. The main goal of RESTful web services is to
make web services more effective. RESTful web services try to define services using
the different concepts that are already present in HTTP. REST is an architectural
approach, not a protocol.

It does not define the standard message exchange format. We can build REST
services with both XML and JSON. JSON is more popular format with REST. The key
abstraction is a resource in REST. A resource can be anything. It can be accessed
through a Uniform Resource Identifier (URI). For example:

The resource has representations like XML, HTML, and JSON. The current state
capture by representational resource. When we request a resource, we provide the
representation of the resource. The important methods of HTTP are:

o GET: It reads a resource.


o PUT: It updates an existing resource.
o POST: It creates a new resource.
o DELETE: It deletes the resource.

o POST /users: It creates a user.

o GET /users/{id}: It retrieves the detail of a user.

o GET /users: It retrieves the detail of all users.

o DELETE /users: It deletes all users.

o DELETE /users/{id}: It deletes a user.

o GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.

RESTful Service Constraints

o There must be a service producer and service consumer.


o The service is stateless.
o The service result must be cacheable.
o The interface is uniform and exposing resources.
o The service should assume a layered architecture.

Advantages of RESTful web services


o RESTful web services are platform independent.
o It can be written in any programming language and can be executed on any
platform.
o It provides different data format like JSON, text, HTML, and XML.
o It is fast in comparison to SOAP because there is no strict specification like
SOAP.
o These are reusable.
o They are language neutral.

You might also like