Unit 4 Spring Web Technology Notes
Unit 4 Spring Web Technology Notes
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.
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.
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.
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
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
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.
Test
This layer provides support of testing with JUnit and TestNG.
Context
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.
The instrumentation module provides support to class instrumentation and classloader implementations.
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
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.
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:
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.
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.
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 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.
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.
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.
In this section, we are going to discuss some important Spring Boot Annotation that we will use later in this tutorial.
Example
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.
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.
@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.
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.
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 .
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"/>
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>
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=""/>
</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());
}
}