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

Unit-5-Spring Framework

Java spring frame work for aktu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Unit-5-Spring Framework

Java spring frame work for aktu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit-5

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.

Dependency Injection is the method of providing


Spring IoC is achieved through Dependency
the dependencies and Inversion of Control is the
Injection.
end result of Dependency 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.

Aspect-Oriented Programming, Dependency look


In case of any changes in business requirements,
up are other ways to implement Inversion of
no code change is required.
Control.
Spring Dependency Injection
• Dependency Injection (DI) is a design pattern that allows you to
decouple your code by making it easier to create and manage objects.
• In Spring, DI is implemented using the Inversion of Control (IoC)
container. The IoC container is responsible for creating and managing
objects, and it injects them into your code when needed.
• Dependency Injection is a fundamental aspect of the Spring framework,
through which the Spring container “injects” objects into other objects
or “dependencies”.
There are two types of Spring Dependency Injection.
• Setter Dependency Injection (SDI)
• Constructor Dependency Injection (CDI)
// Dependecy Injection Using Constructor
Dependency Injection using
Setter Method
Setter Method DI Constructor DI
Dependencies are injected Dependencies are injected
into class through setter into a class through
methods constructor
More readable Less readable
More Flexible Less Flexible
1. Create Maven project

2. Select Catlog and archtype as


marked
3. Provide group id and artifact Id

4. Press finish

*(Internet must be on)

5. Open pom.xml(project object model)


6. Add dependencies to <dependencies> tag
Press crtl+s to save the pom.xml file(all dependencies will be downloaded automatically)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.8</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.8</version>
</dependency>

7. Check Project structure


package com.test.DIDemo;
public class Employee {
//POJO CLASS:FULLY E NCASULATED CLASS
8. Create new class Employee private int empId;
private String name;
private String dept;
public Employee(int empId, String name, String dept) {
super();
this.empId = empId;
this.name = name;
this.dept = dept;
}
public int getEmpId() {
return empId;
9. Create new xml file }
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
<?xml version="1.0" encoding="UTF-8"?>
this.name = name;
<beans xmlns="http://www.springframework.org/schema/beans"
}
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" public String getDept() {
xsi:schemaLocation=" return dept;
http://www.springframework.org/schema/beans }
http://www.springframework.org/schema/beans/spring-beans.xsd"> public void setDept(String dept) {
<bean class="com.test.DIDemo.Employee" name="stud1"> this.dept = dept;
<property name="id" value="1" /> }
<property name="name" value="Raju" /> }
<property name="dept" value="Sales" />
</bean>

</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

<bean class="com.test.DIDemo.Employee" name="stud1"


scope="request">
<property…
</bean>
Autowiring
• Autowiring in the Spring framework can inject dependencies
automatically.
• The Spring container detects those dependencies specified in
the configuration file and the relationship between the
beans.This is referred to as Autowiring in Spring.
• Autowiring in Spring internally uses constructor injection.
• An autowired application requires fewer lines of code
comparatively but at the same time, it provides very little
flexibility to the programmer.
Modes Description
This mode tells the framework that autowiring is not supposed to be done. It is the
No
default mode used by Spring.

byName It uses the name of the bean for injecting dependencies.

byType It injects the dependency according to the type of bean.

Constructor It injects the required dependencies by invoking the constructor.

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.

<bean id="state" class=“pack.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class=“pack.City" autowire="byName"></bean>

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.

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="constructor"></bean>

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.

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="autodetect"></bean>
class City { package com.test.DemoProject;
private int id; Auto wiring example import org.springframework.beans.factory.annotation.Autowired;
private String name; public class State {
private State s; dependency private String name;
public City() {
public String getName() { return name; }
}
public void setName(String s) { this.name = s; }
public int getID() { return id; }
public void setId(int eid) { this.id = eid; } @Override
public String getName() { return name; } public String toString() {
public void setName(String st) { this.name = st; } return "State [name=" + name + "]";
public State getS() { }
return s; public State(String name) {
} super();
public void setS(State s) { this.name = name;
this.s = s; }
} public State() {
public int getId() {
super();}
return id;
}
}
public City(State s) {
super(); package com.test.DemoProject; //main
this.s = s; import org.springframework.context.ApplicationContext;
} import
public City(int id, String name, State s) {
org.springframework.context.support.ClassPathXmlApplicationContext;
super();
this.id = id;
public class Test {
this.name = name; public static void main(String[] args) {
this.s = s; ApplicationContext context = new
} ClassPathXmlApplicationContext("/com/test/DemoProject/config1.xml");
@Override City city=context.getBean("city", City.class);
public String toString() { System.out.println(city);
return "City [id=" + id + ", name=" + name + ", s=" + s + "]"; }
} }
}
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<beans <beans
xmlns="http://www.springframework.org/schema/beans xmlns="http://www.springframework.org/schema/beans"
" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance"
instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema
xmlns:context="http://www.springframework.org/sche /context"
ma/context" xsi:schemaLocation="http://www.springframework.org/s
xsi:schemaLocation="http://www.springframework.org chema/beans
/schema/beans http://www.springframework.org/schema/beans/spring-
http://www.springframework.org/schema/beans/spring beans.xsd
-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring
http://www.springframework.org/schema/context/spri -context.xsd">
ng-context.xsd"> <bean id="s" class="com.test.DemoProject.State" >
<bean id="s" class="com.test.DemoProject.State" > <property name="name" value="UP" />
<property name="name" value="UP" /> </bean>
</bean> <bean name="city" class="com.test.DemoProject.City"
<bean name="city" autowire="byName">
class="com.test.DemoProject.City" <property name="id" value="11" />
autowire="constructor"> <property name="name" value="Washington, D.C." />
<property name="id" value="11" /> </bean>
<property name="name" value="Washington, D.C." /> </beans>
</bean>
</beans>
@autowired
There are three ways to apply the @Autowired annotation:
NOTE: PUT FOLLOWING LINE IN CONFIG.XML FILE
<context:annotation-config/>
1. On a field: This is the most common way to use the @Autowired annotation. Simply annotate the field with
@Autowired and Spring will inject an instance of the dependency into the field when the bean is created.

public class MyBean {


@Autowired
private MyDependency dependency;
}

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.

public class MyBean {


private MyDependency dependency;
@Autowired
public void setDependency(MyDependency dependency) {
this.dependency = dependency;
}
}

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

You might also like