0% found this document useful (0 votes)
14 views37 pages

Spring Basics Lecture3 4kAJ002

The document provides an overview of key concepts in Spring Framework, including Beans Autowiring, Annotation Based Configuration, AOP, and Spring MVC. It explains various autowiring modes, the use of annotations for dependency injection, and the structure and advantages of Spring MVC architecture. Additionally, it details the role of DispatcherServlet and the configuration needed for building a Spring MVC application.
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)
14 views37 pages

Spring Basics Lecture3 4kAJ002

The document provides an overview of key concepts in Spring Framework, including Beans Autowiring, Annotation Based Configuration, AOP, and Spring MVC. It explains various autowiring modes, the use of annotations for dependency injection, and the structure and advantages of Spring MVC architecture. Additionally, it details the role of DispatcherServlet and the configuration needed for building a Spring MVC application.
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/ 37

By

Sudha Agarwal
INDEX
 Beans Autowiring
 Annotation Based Configuration
 AOP with Spring
 Spring MVC
Beans Auto-Wiring
You have learnt how to declare beans using the <bean> element
and inject <bean> using <constructor-arg> and <property> elements
in XML configuration file.

The Spring container can autowire relationships between


collaborating beans without using <constructor-arg> and <property>
elements, which helps cut down on the amount of XML configuration
you write for a big Spring-based application.

Autowiring can't be used to inject primitive and string values. It


works with reference only.
Autowiring Modes
no
This is default setting which means no autowiring and you should
use explicit bean reference for wiring. You have nothing to do special
for this wiring.

byName
Autowiring by property name. Spring container looks at the
properties of the beans on which autowire attribute is set to byName
in the XML configuration file. It then tries to match and wire its
properties with the beans defined by the same names in the
configuration file.
Autowiring Modes
byType
Autowiring by property datatype. Spring container looks at the
properties of the beans on which autowire attribute is set to byType in
the XML configuration file. It then tries to match and wire a property if
its type matches with exactly one of the beans name in configuration
file. If more than one such beans exists, a fatal exception is thrown.

constructor
Similar to byType, but type applies to constructor arguments. If
there is not exactly one bean of the constructor argument type in the
container, a fatal error is raised.

autodetect
Spring first tries to wire using autowire by constructor, if it does not
work, Spring tries to autowire by byType.
Annotation Based Configuration
Starting from Spring 2.5 it became possible to configure the
dependency injection using annotations.

So instead of using XML to describe a bean wiring, you can move
the bean configuration into the component class itself by using
annotations on the relevant class, method, or field declaration.

Annotation injection is performed before XML injection. Thus, the


latter configuration will override the former for properties wired
through both approaches.
Annotation Based Configuration
Annotation wiring is not turned on in the Spring container by default.
So, before we can use annotation-based wiring, we will need to
enable it in our Spring configuration file.
Annotation Based Configuration
Once <context:annotation-config/> is configured, you can start
annotating your code to indicate that Spring should automatically wire
values into properties, methods, and constructors.
Annotation Based Configuration
@Required
The @Required annotation applies to bean property setter methods.

@Autowired
The @Autowired annotation can apply to bean property setter
methods, non-setter methods, constructor and properties.

@Qualifier
The @Qualifier annotation along with @Autowired can be used to
remove the confusion by specifiying which exact bean will be wired.

JSR-250 Annotations
Spring supports JSR-250 based annotations which include
@Resource, @PostConstruct and @PreDestroy annotations.
AOP with Spring
One of the key components of Spring Framework is the Aspect
oriented programming (AOP) framework.

Aspect-Oriented Programming entails breaking down program logic


into distinct parts called so-called concerns.

The functions that span multiple points of an application are called


cross-cutting concerns and these cross-cutting concerns are
conceptually separate from the application's business logic.

There are various common good examples of aspects like logging,


auditing, declarative transactions, security, caching, etc.
AOP with Spring
The key unit of modularity in OOP is the class, whereas in AOP the
unit of modularity is the aspect.

Dependency Injection helps you decouple your application objects


from each other and AOP helps you decouple cross-cutting concerns
from the objects that they affect.

Spring AOP module provides interceptors to intercept an


application. For example, when a method is executed, you can add
extra functionality before or after the method execution.
AOP Terminologies
Aspect
This is a module which has a set of APIs providing cross-cutting
requirements. For example, a logging module would be called AOP
aspect for logging. An application can have any number of aspects
depending on the requirement.

Join point
This represents a point in your application where you can plug-in
the AOP aspect. You can also say, it is the actual place in the
application where an action will be taken using Spring AOP
framework.
AOP Terminologies
Advice
This is the actual action to be taken either before or after the
method execution. This is an actual piece of code that is invoked
during the program execution by Spring AOP framework.

Pointcut
This is a set of one or more join points where an advice should be
executed. You can specify pointcuts using expressions or patterns as
we will see in our AOP examples.

Introduction
An introduction allows you to add new methods or attributes to the
existing classes.
AOP Terminologies
Target object
The object being advised by one or more aspects. This object will
always be a proxied object, also referred to as the advised object.

Weaving
Weaving is the process of linking aspects with other application
types or objects to create an advised object. This can be done at
compile time, load time, or at runtime.
Types of Advice
before
Run advice before the a method execution.

after
Run advice after the method execution, regardless of its outcome.

after-returning
Run advice after the a method execution only if method completes
successfully.

after-throwing
Run advice after the a method execution only if method exits by
throwing an exception.

around
Run advice before and after the advised method is invoked.
Spring mvc
The Spring Web MVC framework provides Model-View-Controller
(MVC) architecture and ready components that can be used to
develop flexible and loosely coupled web applications. The MVC
pattern results in separating the different aspects of the application
(input logic, business logic, and UI logic), while providing a loose
coupling between these elements.

The Model encapsulates the application data and in general they


will consist of POJO.

The View is responsible for rendering the model data and in general
it generates HTML output that the client's browser can interpret.

The Controller is responsible for processing user requests and


building an appropriate model and passes it to the view for rendering.
The DispatcherServlet
The Spring Web model-view-controller (MVC) framework is
designed around a DispatcherServlet that handles all the HTTP
requests and responses.
The DispatcherServlet
All the incoming request is intercepted by the DispatcherServlet
that works as the front controller.

The DispatcherServlet gets an entry of handler mapping from the


XML file and forwards the request to the controller.

The controller returns an object of ModelAndView.

The DispatcherServlet checks the entry of view resolver in the XML


file and invokes the specified view component.
The DispatcherServlet
All the components, i.e. HandlerMapping, Controller, and
ViewResolver are parts of WebApplicationContext which is an
extension of the plainApplicationContext with some extra features
necessary for web applications.
Advantages of Spring MVC
Separate roles - The Spring MVC separates each role, where the
model object, controller, command object, view resolver,
DispatcherServlet, validator, etc. can be fulfilled by a specialized
object.

Light-weight - It uses light-weight servlet container to develop and


deploy your application.

Powerful Configuration - It provides a robust configuration for both


framework and application classes that includes easy referencing
across contexts, such as from web controllers to business objects and
validators.
Advantages of Spring MVC
Rapid development - The Spring MVC facilitates fast and parallel
development.

Reusable business code - Instead of creating new objects, it


allows us to use the existing business objects.

Easy to test - In Spring, generally we create JavaBeans classes


that enable you to inject test data using the setter methods.

Flexible Mapping - It provides the specific annotations that easily


redirect the page.
Spring Web MVC Example
The steps to build a spring mvc framework project are:

Load the spring jar files or add dependencies in the case of Maven
Create the controller class
Provide the entry of controller in the web.xml file
Define the bean in the separate XML file
Display the message in the JSP page
Start the server and deploy the project
Directory Structure of Spring
MVC
Required Maven Dependency
 You need to load:
1. Spring Core jar files
2. Spring Web jar files
3. JSP + JSTL jar files

If you are using Maven, you don't need to add jar files. Now, you
need to add maven dependency to the pom.xml file.
Create the controller
class
To create the controller class, we are using two annotations
@Controller and @RequestMapping.

The @Controller annotation marks this class as Controller.

The @Requestmapping annotation is used to map the class with


the specified URL name. This annotation maps HTTP requests to
handler methods of MVC and REST controllers.
@RequestMapping
In Spring MVC applications, the RequestDispatcher (Front
Controller Below) servlet is responsible for routing incoming HTTP
requests to handler methods of controllers.

When configuring Spring MVC, you need to specify the mappings


between the requests and handler methods.
@RequestMapping
In Spring MVC applications, the RequestDispatcher (Front
Controller Below) servlet is responsible for routing incoming HTTP
requests to handler methods of controllers.

When configuring Spring MVC, you need to specify the mappings


between the requests and handler methods.
@RequestMapping
To configure the mapping of web requests, you use the
@RequestMapping annotation.

With the preceding code, requests to /home will be handled by get()


while request to /home/index will be handled by index().
@RequestParam
The @RequestParam annotation is used with @RequestMapping
to bind a web request parameter to the parameter of the handler
method.
The @RequestParam annotation can be used with or without a
value. The value specifies the request param that needs to be
mapped to the handler method parameter

An example URL is this:


localhost:8090/home/id?id=5
@RequestMapping with HTTP
Method
The Spring MVC @RequestMapping annotation is capable of
handling HTTP request methods, such as GET, PUT, POST,
DELETE, and PATCH.
By default all requests are assumed to be of HTTP GET type.
Provide the entry of
controller in the web.xml
In this xml file, we are specifying the servlet class DispatcherServlet
that acts as the front controller in Spring Web MVC. All the incoming
request for the html file will be forwarded to the DispatcherServlet.
Define the bean in the xml
This is the important configuration file where we need to specify the
View components.

The context:component-scan element defines the base-package


where DispatcherServlet will search the controller class.

This xml file should be located inside the WEB-INF directory.


Display the message in the
JSP page
This is the simple JSP page, displaying the message returned by
the Controller.
View resolver
All MVC frameworks provide a way of working with views.

Spring does that via the view resolvers, which enable you to render
models in the browser without tying the implementation to a specific
view technology.

The ViewResolver maps view names to actual views.

InternalResourceViewResolver is the view resolver, we can provide


view pages location through prefix and suffix properties. So all our
JSP pages should be in /WEB-INF/views/ directory.
ContextLoaderListener
In Spring Web Applications, there are two types of container, each
of which is configured and initialized differently. One is the
"Application Context" and the other is the "Web Application
Context".

Application Context is the container initialized by a


ContextLoaderListener or ContextLoaderServlet defined in the
web.xml and the configuration would look something like this:
ContextLoaderListener
In the above configuration, we asking spring to load all files from the
classpath that match /WEB-INF/dispatcher-servlet.xml and create an
Application Context from it.

This context might, for instance, contain components such as


middle-tier transactional services, data access objects, or other
objects that you might want to use (and re-use) across the application.
There will be one application context per application.

ContextLoaderListener creates a root web-application-context for


the web-application and puts it in the ServletContext. This context can
be used to load and unload the spring-managed beans.
ContextLoaderListener
ContextLoaderListener ties the ApplicationContext lifecycle to
ServletContext lifecycle and automate the creation of
ApplicationContext.

ApplicationContext is the place for Spring beans and we can


provide it’s configuration through contextConfigLocation context
parameter.

DispatcherServlet is the controller class for Spring MVC application


and all the client requests is getting handled by this servlet. The
configuration are being loaded from servlet-context.xml file.

You might also like