Spring Notes (Unit-5)
Spring Notes (Unit-5)
Spring Framework
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.
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.
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
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
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
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.
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.
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.
Suppose you want to add logging to the add method of a Calculator class.
java
Copy code
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
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");
}
}
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">
<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();
}
}
java
Copy code
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
What is a Bean?
Characteristics of a Bean
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
Example:
java
Copy code
@Configuration
public class AppConfig {
@Bean
@Scope("prototype")
public MyPrototypeBean myPrototypeBean() {
return new MyPrototypeBean();
}
}
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();
}
}
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();
}
}
java
Copy code
@Configuration
public class AppConfig {
@Bean
@Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode =
ScopedProxyMode.TARGET_CLASS)
public MyApplicationBean myApplicationBean() {
return new MyApplicationBean();
}
}
Example:
java
Copy code
@Configuration
public class AppConfig {
@Bean
@Scope(value = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyWebSocketBean myWebSocketBean() {
return new MyWebSocketBean();
}
}
Summary
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. @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.
The primary comparison between Spring and Spring Boot are discussed below:
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.
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.
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: