Unit-5-Spring Framework
Unit-5-Spring Framework
Spring Framework
Spring Framework
• Open-Source Framework
• Standalone and Enterprise application can be developed
• Released in 2003(initial), 2004(production) developed by Rod
Johnson
Advantages
• Modular and lightweight(lightweight and easy to maintain applications)
• Flexible configuration(supports Java-based, XML-based and
annotation-based configurations)
• Dependency Injection(dependency management)
• Aspect oriented programming(Allows developers to separate code from
the features like logging, transactions, security etc.)
• Easy database handling(reduce boilerplate code increase efficiency)
• Testing support
• Security(robust framework for implementing authentication,
authorization)
• High integration capabilities(with other frameworks and technologies
like angular, react, JMS, SOAP, REST)
• High Scalability
• Open-Source
Modules
The Spring
Framework consists
of features organized
into about 20
modules. These
modules are grouped
into Core Container,
Data
Access/Integration,
Web, AOP (Aspect
Oriented
Programming),
Instrumentation, and
Test, as shown in the
following diagram.
Dependency?
• Example of dependency
• Code has very high degree of coupling due to aggregation
• To create Object of class Person, we depend on Address Object,
and to create Address object, we need contact
Working of Spring Container
Spring Container
• The Spring container is the core of the Spring Framework.
• Manages Bean Objects(create, initialize, destroy)[Life cycle of
bean]
• It is responsible for creating, configuring, and managing the
objects that make up your application.
• The container uses a technique called dependency injection to
manage the relationships between objects.
• Transaction Management
Spring container are of TWO TYPES
1. BeanFactory(old Method)
2. ApplicationContext(new Method)
Working of Spring Container
Working of Spring Container
Spring Framework Example with Java Configuration file
Inversion of Control (IoC)
• Inversion of Control (IoC) is a design principle that emphasizes keeping Java
classes independent of each other.
• IoC is achieved through Dependency Injection (DI).
• IoC refers to transferring the control of objects and their dependencies from the
main program to a container or framework.
• The IoC container uses two primary mechanisms to work:
Bean instantiation:
• The IoC container is responsible for creating and configuring beans. This can be
done through XML configuration, Java annotations, or a combination of both.
Dependency injection:
• The IoC container injects dependencies into beans. This means that the IoC
container is responsible for providing beans with the objects they need to
function.
Spring IoC (Inversion of Control) Spring Dependency Injection
Spring IoC Container is the core of Spring Spring Dependency injection is a way to inject the
Framework. It creates the objects, configures and dependency of a framework component by the
assembles their dependencies, manages their entire following ways of spring: Constructor Injection
life cycle. and Setter Injection.
Spring helps in creating objects, managing objects, Spring framework helps in the creation of loosely-
configurations, etc. because of IoC (Inversion of coupled applications because of Dependency
Control). Injection.
IoC is a design principle where the control flow of Dependency Injection is one of the subtypes of the
the program is inverted. IOC principle.
4. Press finish
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.8</version>
</dependency>
</beans>
10. See project structure now
9. Update App.java package com.test.DIDemo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
ApplicationContext context=new
ClassPathXmlApplicationContext("com/test/DIDemo/config.xml");
Employee employee=(Employee)context.getBean("stud1");
System.out.println(employee);
} Dependency injection
}
10.
execute App.java
Aspect-Oriented Programming (AOP)
• Aspect-Oriented Programming (AOP) is a programming technique that allows developers
to modularize cross-cutting concerns. Cross-cutting concerns are tasks that affect
multiple parts of a program, such as logging, security, and transaction management.
• AOP allows developers to separate these concerns from the main program logic. This
makes the code more modular, reusable, and maintainable.
• Spring AOP is a popular implementation of AOP. It provides a simple and powerful way to
write custom aspects.
• Spring provides simple and powerful ways of writing custom aspects by using either
a schema-based approach or the @AspectJ annotation style. Both of these styles offer
fully typed advice and use of the AspectJ pointcut language while still using Spring AOP
for weaving.
• AOP is used in the Spring Framework to:
• Provide declarative enterprise services. The most important such service is declarative
transaction management.
• Let users implement custom aspects, complementing their use of OOP with AOP.
Benefits of using AOP
Modularity:
• AOP allows developers to separate cross-cutting concerns from
the main program logic. This makes the code more modular,
reusable, and maintainable.
Reusability:
• Aspects can be reused across multiple projects. This saves time
and effort, and it can help to improve the consistency of code.
Maintainability:
• AOP makes it easier to maintain code. This is because cross-
cutting concerns are separated from the main program logic. This
makes it easier to understand and modify the code.
WebSocket API
Spring Framework provides a WebSocket API that adapts to various
WebSocket engines, including Tomcat, Jetty, GlassFish, WebLogic, and
Undertow. This API allows developers to easily implement WebSocket-
based applications. The Spring Framework also provides a number of
features that make it easy to develop WebSocket-based applications,
including:
• A messaging framework that supports STOMP, a text-oriented
messaging protocol that can be used over any reliable 2-way
streaming network protocol such as TCP and WebSocket.
• A JavaScript client library that makes it easy to develop WebSocket-
based web applications.
• A number of pre-built WebSocket-based applications, such as a chat
application and a stock ticker.
BEAN SCOPE
• Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will be
instantiated, how long does that object live, and how many objects will be created for that bean
throughout. Basically, it controls the instance creation of the bean and it is managed by the spring
container.
• In the Spring Framework, a bean's scope determines how long it lives and how many instances
of it are created.
• The default scope is singleton, Only one instance will be created for a single bean definition per
Spring IoC container and the same object will be shared for each request made for that bean.
• The prototype scope A new instance will be created for a single bean definition every time a
request is made for that bean. This is useful for beans that are not thread-safe or that need to be
customized for each request.
• The request scope creates a new instance of the bean for each HTTP request. This is useful for
beans that need to be associated with a specific request, such as a database connection or a
shopping cart.
• The session scope creates a new instance of the bean for each user session. This is useful for
beans that need to be associated with a specific user, such as a user profile or a shopping cart.
• The global session scope creates a new instance of the bean for each user session across all
applications in the same cluster. This is useful for beans that need to be shared across multiple
applications, such as a user profile or a shopping cart.
BEAN SCOPE
• You can specify the scope of a bean using the @Scope annotation. For
example, the following code creates a bean with the prototype scope:
@Scope("prototype")
public class MyBean {
// ...
}
OR
Autodetect(depre
The autodetect mode uses two other modes for autowiring – constructor and byType.
cated in Spring 3)
1. No
This mode tells the framework that autowiring is not supposed to be done. It is the default
mode used by Spring.
2. byName
It uses the name of the bean for injecting dependencies. However, it requires that the name of the
property and bean must be the same. It invokes the setter method internally for autowiring.
3. byType
It injects the dependency according to the type of the bean. It looks up in the configuration file for
the class type of the property. If it finds a bean that matches, it injects the property. If not, the
program throws an error. The names of the property and bean can be different in this case. It
invokes the setter method internally for autowiring.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byType"></bean>
4. constructor
It injects the required dependencies by invoking the constructor. It works similar to the “byType” mode but it looks for the
class type of the constructor arguments. If none or more than one bean are detected, then it throws an error, otherwise,
it autowires the “byType” on all constructor arguments.
5. autodetect
The autodetect mode uses two other modes for autowiring – constructor and byType. It first tries to autowire via the
constructor mode and if it fails, it uses the byType mode for autowiring. It works in Spring 2.0 and 2.5 but is deprecated
from Spring 3.0 onwards.
2. On a constructor: You can also use the @Autowired annotation on a constructor. This will cause Spring to
inject an instance of the dependency into the constructor when the bean is created.
public class MyBean {
private MyDependency dependency;
@Autowired
public MyBean(MyDependency dependency) {
this.dependency = dependency;
}
}
3. On a setter method: You can also use the @Autowired annotation on a setter method. This will cause Spring to
inject an instance of the dependency into the setter method when the bean is created.
The @Autowired annotation can be used on any field, constructor, or setter method that is declared in a Spring
bean. The dependency that is injected must be a Spring bean itself.
Life Cycle Call backs
• Bean life cycle is managed by the spring container. When we run the
program then, first of all, the spring container gets started. After that, the
container creates the instance of a bean as per the request, and then
dependencies are injected. And finally, the bean is destroyed when the
spring container is closed. Therefore, if we want to execute some code on
the bean instantiation and just after closing the spring container, then we
can write that code inside the custom init() method and
the destroy() method.
Example: Life Cycle Call Back