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

Unit 4 Spring Web Technology Notes

wt notes

Uploaded by

Shivansh Plays
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Unit 4 Spring Web Technology Notes

wt notes

Uploaded by

Shivansh Plays
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

lOMoARcPSD|30563322

UNIT 4 spring - Web Technology Notes

web technology (Dr. A.P.J. Abdul Kalam Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)
lOMoARcPSD|30563322

UNIT-4 SPRING

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, Tapestry, EJB, JSF, 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:

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

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.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

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.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

Spring Module
The Spring framework comprises of many modules such as core, beans, context, expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM,
JMS, Transaction, Web, Servlet, Struts etc. These modules are grouped into Test, Core Container, AOP, Aspects, Instrumentation, Data Access /
Integration, Web (MVC / Remoting) as displayed in the following diagram.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

Test
This layer provides support of testing with JUnit and TestNG.

Spring Core Container


The Spring Core container contains core, beans, context and expression language (EL) modules.

Core and Beans

These modules provide IOC and Dependency Injection features.

Context

This module supports internationalization (I18N), EJB, JMS, Basic Remoting.

Expression Language

It is an extension to the EL defined in JSP. It 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.

AOP, Aspects and Instrumentation


These modules support aspect oriented programming implementation where you can use Advices, Pointcuts etc. to decouple the code.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

The aspects module provides support to integration with AspectJ.

The instrumentation module provides support to class instrumentation and classloader implementations.

Data Access / Integration


This group comprises of JDBC, ORM, OXM, JMS and Transaction modules. These modules basically provide support to interact with the database.

Web
This group comprises of Web, Web-Servlet, Web-Struts and Web-Portlet. These modules provide support to create web application.

Spring Example
Here, we are going to learn the simple steps to create the first spring application. To run this application, we are not using any IDE. We are simply using
the command prompt. Let's see the simple steps to create the spring application

o create the class


o create the xml file to provide the values
o create the test class
o Load the spring jar files
o Run the test class

1) Create Java class


This is the simple java bean class containing the name property only.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

1. package com.javatpoint;
2.
3. public class Student {
4. private String name;
5.
6. public String getName() {
7. return name;
8. }
9.
10. public void setName(String name) {
11. this.name = name;
12. }
13.
14. public void displayInfo(){
15. System.out.println("Hello: "+name);
16. }
17. }

This is simple bean class, containing only one property name with its getters and setters method. This class contains one extra method named
displayInfo() that prints the student name by the hello message.

2) Create the xml file

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

In case of myeclipse IDE, you don't need to create the xml file as myeclipse does this for yourselves. Open the applicationContext.xml file, and write the
following code:

1. <?xml version="1.0" encoding="UTF-8"?>


2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="studentbean" class="com.javatpoint.Student">
10. <property name="name" value="Vimal Jaiswal"></property>
11. </bean>
12.
13. </beans>

The bean element is used to define the bean for the given class. The property subelement of bean specifies the property of the Student class named
name. The value specified in the property element will be set in the Student class object by the IOC container.

3) Create the test class


Create the java class e.g. Test. Here we are getting the object of Student class from the IOC container using the getBean() method of BeanFactory. Let's
see the code of test class.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.ClassPathResource;
6. import org.springframework.core.io.Resource;
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource resource=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(resource);
12.
13. Student student=(Student)factory.getBean("studentbean");
14. student.displayInfo();
15. }
16. }

The Resource object represents the information of applicationContext.xml file. The Resource is the interface and the ClassPathResource is the
implementation class of the Reource interface. The BeanFactory is responsible to return the bean. The XmlBeanFactory is the implementation class of
the BeanFactory. There are many methods in the BeanFactory interface. One method is getBean(), which returns the object of the associated class.

4) Load the jar files required for spring framework


There are mainly three jar files required to run this application.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

o org.springframework.core-3.0.1.RELEASE-A
o com.springsource.org.apache.commons.logging-1.1.1
o org.springframework.beans-3.0.1.RELEASE-A

DESIGN PATTERN IN SPRING: - Introduction

Design patterns are an essential part of software development. These solutions not only solve recurring problems but also help developers
understand the design of a framework by recognizing common patterns.

Factory Method Pattern


The factory method pattern entails a factory class with an abstract method for creating the desired object.
Often, we want to create different objects based on a particular context.
For example, our application may require a vehicle object. In a nautical environment, we want to create boats, but in an aerospace environment,
we want to create airplanes:

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

Bean Scope:- When you create a bean definition what you are actually creating is a recipe for creating actual instances of the class
defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, just like a class, you can
potentially have many object instances created from a single recipe.

The Spring Framework supports the following five scopes, three of which are available only if you use a web-aware ApplicationContext.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

Sr.No. Scope & Description

1 singleton
This scopes the bean definition to a single instance per Spring IoC container
(default).

2 prototype
This scopes a single bean definition to have any number of object instances.

3 request
This scopes a bean definition to an HTTP request. Only valid in the context of a
web-aware Spring ApplicationContext.

4 session
This scopes a bean definition to an HTTP session. Only valid in the context of a
web-aware Spring ApplicationContext.

5 global-session
This scopes a bean definition to a global HTTP session. Only valid in the context
of a web-aware Spring ApplicationContext.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

Spring Boot Annotations


Spring Boot Annotations is a form of metadata that provides data about a program. In other words, annotations are used to
provide supplemental information about a program. It is not a part of the application that we develop. It does not have a direct effect on the operation
of the code they annotate. It does not change the action of the compiled program.

In this section, we are going to discuss some important Spring Boot Annotation that we will use later in this tutorial.

Core Spring Framework Annotations


@Required: It applies to the bean setter method. It indicates that the annotated bean must be populated at configuration time with the required
property, else it throws an exception BeanInitilizationException.

Example

How to find Nth Highest Salary in SQL

1. public class Machine


2. {
3. private Integer cost;
4. @Required
5. public void setCost(Integer cost)
6. {
7. this.cost = cost;

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

8. }
9. public Integer getCost()
10. {
11. return cost;
12. }
13. }

@Autowired: Spring provides annotation-based auto-wiring by providing @Autowired annotation. It is used to autowire spring bean on setter
methods, instance variable, and constructor. When we use @Autowired annotation, the spring container auto-wires the bean by matching data-type.

Example

1. @Component
2. public class Customer
3. {
4. private Person person;
5. @Autowired
6. public Customer(Person person)
7. {
8. this.person=person;
9. }
10. }

@Configuration: It is a class-level annotation. The class annotated with @Configuration used by Spring Containers as a source of bean definitions.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

Example

1. @Configuration
2. public class Vehicle
3. {
4. @BeanVehicle engine()
5. {
6. return new Vehicle();
7. }
8. }
 @GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a web service endpoint that fetches It
is used instead of using: @RequestMapping(method = RequestMethod.GET)
 @PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create a web service endpoint
that creates It is used instead of using: @RequestMapping(method = RequestMethod.POST)
 @PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a web service endpoint
that creates or updates It is used instead of using: @RequestMapping(method = RequestMethod.PUT)
 @DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It is used to create a web service endpoint
that deletes a resource. It is used instead of using: @RequestMapping(method = RequestMethod.DELETE)
 @PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It is used instead of
using: @RequestMapping(method = RequestMethod.PATCH)
 @RequestBody: It is used to bind HTTP request with an object in a method parameter. Internally it uses HTTP MessageConverters to
convert the body of the request. When we annotate a method parameter with @RequestBody, the Spring framework binds the incoming
HTTP request body to that parameter.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

 @ResponseBody: It binds the method return value to the response body. It tells the Spring Boot Framework to serialize a return an object
into JSON and XML format.

9. @PathVariable: It is used to extract the values from the URI. It is most suitable for the RESTful web service, where the URL contains a path
variable. We can define multiple @PathVariable in a method.
10. @RequestParam: It is used to extract the query parameters form the URL. It is also known as a query parameter. It is most suitable for web
applications. It can specify default values if the query parameter is not present in the URL.
11. @RequestHeader: It is used to get the details about the HTTP request headers. We use this annotation as a method parameter. The optional
elements of the annotation are name, required, value, defaultValue. For each detail in the header, we should specify separate annotations. We
can use it multiple time in a method
12. @RestController: It can be considered as a combination of @Controller and @ResponseBody annotations. The @RestController annotation
is itself annotated with the @ResponseBody annotation. It eliminates the need for annotating each method with @ResponseBody.
13. @RequestAttribute: It binds a method parameter to request attribute. It provides convenient access to the request attributes from a controller
method. With the help of @RequestAttribute annotation, we can access objects that are populated on the server-side.

Spring Bean Lifecycle Callback Methods


In Spring framework it is the Spring container that is responsible for instantiating beans, setting bean properties, wiring
dependencies and managing the complete bean lifecycle from its instantiation to the time bean is destroyed.
Following is sequence of a bean lifecycle in Spring:

1. Instantiate– First the spring container finds the bean’s definition from the XML file and instantiates the bean..
2. Populate properties– Using the dependency injection, spring populates all of the properties as specified in the bean definition..
3. Set Bean Name– If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
4. Set Bean factory– If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

5. Pre Initialization– Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls
postProcesserBeforeInitialization() method.
6. Initialize beans– If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the
specified initialization method is called.
7. Post Initialization– If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
8. Ready to use– Now the bean is ready to use by the application.
9. Destroy– If the bean implements DisposableBean , it will call the destroy() method .

Bean configuration style:-

Bootstrapping JavaConfig from XML with ConfigurationPostProcessor

You may desire or be required to use XML as the primary mechanism for configuring the container, but wish to selectively
use @Configuration classes to define certain beans. For such cases, JavaConfig provides ConfigurationPostProcessor, a
Spring BeanPostProcessor capable of processing @Configuration classes.

<beans>
<!-- first, define your individual @Configuration classes as beans -->
<bean class="com.myapp.config.AppConfig"/>
<bean class="com.myapp.config.DataConfig"/>

<!-- be sure to include the JavaConfig bean post-processor -->


<bean class="org.springframework.config.java.process.ConfigurationPostProcessor"/>
</beans>

Then, bootstrap an XML ApplicationContext:

ApplicationContext context = new ClassPathXmlApplicationContext("application-config.xml");

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

The beans defined in AppConfig and DataConfig will be available via context.

Configuring configurations

An added benefit that comes along with bootstrapping JavaConfig from XML is that the configuration bean instances are eligible, just
as any other bean, for dependency injection:

<beans>
<!-- a possible "configurable configuration" -->
<bean class="org.my.company.config.AppConfiguration">
<property name="env" value="TESTING"/>
<property name="monitoring" value="true"/>
<property name="certificates" value="classpath:/META-INF/config/MyCompany.certs"/>
</bean>
<!-- JavaConfig post-processor -->
<bean class="org.springframework.config.java.process.ConfigurationPostProcessor"/>
</beans>

Bootstrapping XML from JavaConfig with @ImportXml

The @ImportXml annotation is provided to support importing beans defined in XML into @Configuration classes.

datasource-config.xml:
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="username" value="sa"/>
<property name="password" value=""/>

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

</bean>
</beans>

@Configuration
@AnnotationDrivenConfig // enable the @Autowired annotation
@ImportXml("classpath:com/company/app/datasource-config.xml")
public class Config {
// autowire the DataSource bean declared in datasource-config.xml
@Autowired DataSource dataSource;

@Bean
public FooRepository fooRepository() {
// inject the autowired-from-XML dataSource
return new JdbcFooRepository(dataSource);
}

@Bean
public FooService fooService() {
return new FooServiceImpl(fooRepository());
}
}

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)


lOMoARcPSD|30563322

Downloaded by Shivansh Plays (shivanshsaxena2910@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy