Вы находитесь на странице: 1из 30

IOC containers

1.Used to read the configuration file


2.create the bean objects
3.provide the bean objects to application

Two types of IOC containers


1.Beanfactory ----lazy loader
2.ApplicationContext -----eager loading

BeanFactory :---
1.fundamental or base conatiner provided by spring framework.
2.Provide the basic functionalities to spring framework like creation
,maintenacnce of bean objects as provided in configuration file
3.To represent BeanFactory IOC container Spring framework has provided

BeanFactory(I)
org.springframework.beans.factory.Beanfactory interface

4. The implementation class of BeanFactory Interface is


org.springframework.beans.factory.xml.XmlBeanFactory

5.Steps for using the BeanFactory IOC container

1.Create Resource Object


2.create BeanFactory Object
3.Get bean oject and access the business logic

Note: XmlBeanFactory has been deprecated

ApplicationContext :---
1.AplicationContext is an extension of BeanFactory Container
2.Provides some advanced features of internationlization ,Event Hnadling,
along with the fundamental functionalities BeanFactory is providing
3.Represented by Interface org.springFramework.context.ApplicationContext
(Interface)
4.ApplicationContext is child interface of BeanFactory

ApplicationContext actions:
-->configuraaion file loading
-->configuration file parsing
-->read data from configuration file
-->Recognize all bean configurations
-->get bean name and location of all the bean classes
-->bean class loading-->create bean object -->bean initialization-->storing bean
objects in form of key-->value pairs( id name of property tag (Key)-->Class
Objects(Value)))

Beans Scope : --
In J2SEE we can define the scopes using access modifiers like
private,public,protected ,default
similarly in Spring we can define bean scopes :--
1.Singleton Scope (default )
2.prototype
3.request scope
4.session scope
5.globalSession scope
6.application scope
7.webSocket scope

#To define the Spring configuration file without XML file by using Annotations

@Configuration ----class level annotation


@Bean(name="bean" ,autowire=Autowire.byType) ------method level annotation
public BeanObject method(){
return new Bean();}

Bean Life Cycle: ----


-----------------------------------------------
#1.Bean Loading ------------IOC container will load the Bean class bytecode firat
locating in local ,then rt.jar finally from env. variables by reflection api

Class c= Class.forName("com.core.MyBean");

#2.Bean Instantiation

c.newInstance();

Bean Instantion occurs by 3 ways: --


1.By Constructor
2.Static Factory method
3.Instance factory method

#3.Bean Initialization
#4.Bean DeInstantiation

Bean Initialization and Destruction


IOC container will initialize the Beans and destroy the Beans.
Bean destruction occurs when Business logic is executed or IOC conatiner is
shutdown .
Three ways to perform Bean initialization and Bean Destruction
1.By using Custom Initialazation and Destruction methods
2.By using InitializingBean and DsiposableBean callback interfaces
3.By using @PostConstruct and @PreDestry annotations

1.By using Custom initialization and destruction Method


In this approach we have to define the custom Initialization and destruction
methods while bean initialaiztion in Config file. using the "init-method" and
"destroy-method" as bean attributes

<bean init-method="initMethod" destroy-method="destroyMethod" id="secondbean"


class="com.test.MySecondBean" factory-bean="mybeanfactory" factory-
method="getSecondBeanObject">
"

#2.By using IniitalizingBean, its an callback method ,provides follwing methodfor


Bean Initialization

public void afterPropertiesSet()throws Exception


NOTE: -- This method will be executed by IOC container after calling all the
setXXX() methods or All Setters of Bean class by ApplicationContext.

In Spring framework ,DisposableBean is callback interface ,it provides follow


ing method to execute while destruction of Beans

public void destroy();

#3. By @PostConstruct and @PreDestroy Annotations


@PostConstruct Annotation will make a method to call by IOC container while
initializaing the Bean

@PreDestroy Annotation will call that method while bean destruction

NOTE: ----
In general We can do Bean initializazation and destruction using all or one of
the above approaches ,But if we use all above three approaches in a single bean at
same time then the Order of Bean initialization wil be following

a)an Initialization method marked with @PostConstruct Annotation


b)afterPropertiesSet() method provided or implemented by InitializingBean(I)
Interface
c)an initialization method configured with "init-method" in Config File
<bean id="id" class="Bean" init-method="initMethod"/>

###Destruction Order

a)Adestruction method marked by @PreDestroy Annotation


b)destroy() method implemented by implementing the DisposableBean(I) interface
c)A destruction method defined by "destroy-method" in config file

##For calling the init and destroy methods(with same name) for all the Beans we
can mention default-init-method="initMethodNameInAllBeans" deault-destroy-
method="destroyMethodNameInAllBeans" .So while loading the IOC it will call init
destroy methods of all Beans where method is defined after setting all
properties of corresponding bean

--------------------------------------
Bean Inheritance

<bean name="shape" class="com.core.Shape" >


<property name="name" value="shapes"/>
<property name="type" value="triangle"/>
<property name="sides" value="3"/>
</bean>

<bean name="child" ###parent="shape"### class="com.core.Triangle">


<property name="corners" value="3" />
</bean>
#BeanPostProcessor
When ApplicationContext is activated , IOC container will perform some actions
automatically implicitly

1.ApplicationContext will read Bean difinitions from configuration file


2.ApplicationContext will recognize beans classes and creates objects for
beans.
3.ApplicationContext will initialization by executing initialization methods
4.When IOC container is shutdown then bean objects are destroyed .
In Above Bean lifecycle if we want to provide the customization over bean
initializations then we have to us predefined interface
org.springframework.beans.factory.config.BeanPostProcessor"

BeanPostProcessor interface contains following two methods


1.public void postProcessBeforeInitialization(Object bean , String name) throws
BeansException
--->This method will be executed before bean initialization and after bean
instantiation .. ie. before executing init() method if we provide custom
initialization method

2.public void postProcessAfterInitialization(Object bean, String name)throws


BeanException
--->it will be executed after bean initialization .ie after init() method

Nested Beans :--


Declaring a bean configuration in another bean configuration is called as Inner
Bean or Nested beans.

<beans>
<bean id="" class="parentClass">
<property name="innerbean">
<bean id="innerbean" class="Class">
</bean>
</property>
</bean>>
</beans>

#IOC(Inversion of Control)
--------------------------
In general ,if we request a service from a service provider then service
provider has to create the required service and fulfill the request by
creating the service and serving the request to client.

In Spring application ,Inversion of control means service provider will create


the service and inject the requered services in spring application without the
request of client .The control of providing services is transferred to the IOC
Container instead of explicitly creating the Injection of beans.

IOC is available in two forms


==========================
1.Dependency Look-up
2.Dependency Injection
1.Dependency Look-up
In this Service provider will create the service and maintain them in registry
software or in th Containers , where we have to perform the lookup operation
inorder to get the required services.

Two ways to achieve the Dependency Lookup


1.Dependency Pull
In dependency pull, Service provider will create the service and save them in
the registry software , where we have to perform the lookup operation to get
the required service i.e pull the required service from registry software.

Example 1 : when we start the application srevers like Weblogic, JBOSS ,


WebSphere and Glassfish automatically .Application server will create the
DataSource object and keep them DataSource oject in JNDI server as per the
server settings made in Application server.For this we have to perform
lookup(--) operation over JNDI server on the basis of logical name inorder to
get the required DataSource objecct

Example 2 : In RMI Applications , User defined Registry Application will crreate


the Remote object and save that remote object in RMIRegistry with a particular
logical name , To get the required Remote object in Client application we have
to perform lookup operation over RMI Registry on the basis of logical name

2. ContextualizedDEpendency Lookup
In this , Service Provider will create the services and manage the servieces we
have to perform the lookup operation to get the required services from srvice
provider.

Ex. In genaral, in web application , when we start the application server then
container will recognize all the web application and ontaimner will deploy
all the web application into the server. when web application is deployed in
server Container will craete the ServletContext object automatically and
conatiner will manage the ServletContext object , To get the ServletContext
object we have to call getServletContext() method from GenericServlet directly
without using any reference variable , from ServletConfig object refernece
and from ServletRequest object reference , ie performing lookup operation in
Container to get ServletContext object

|Container|

Servlet Loading
|
Servlet Intantiation
|
Servlet Initialization
|
Request Mapping
Request object
Response object
|
ServletDeinstantiation

In this mechanism , Service Provider will create the services and t inject the
required services to the application directly without performing any lookup
operation and without g
etting the rrequest from client .

Example : I web application when we submit the request to particular servlet ,


Container will execute the requested Servlet by performing the servlet life
cycle methods li ke Servlet Loading , Servlet Instantaitoin , Servlet
Initialization , Request processing and servlet deinstantiation . In Servlet
initailization phase Conatiner will create the ServletConfig object and
Conatiner will inject ServletConfig object to servlet program by
init(ServletConfig serConfig) method .Conatiner will create the Request
,Response obbjects and inject them Servlet Program through
service(HttpServletRequest req, HttpServletResponse res) method ,

public class Servlet extends HttpServlet{


ServletConfig serConfig ;

public void init(ServletConfig serConfig ){


this.serConfig = serConfig;
}

public void service(){}


}

There are 2 ways of dependency Injection


1.Constructor DI
2.Setter method DI

1.Constructor DI

Dependent Values are injected via Constructor .

<beans>
<bean id="id" class="class">
<constructor-arg name="arg0" index="0,1,2" type="int,String,double"
value="value" />
</bean>
</beans>

2. Setter Method DI
Dependent values are injected via setter methods

1.p:namespace

In general while doing dependency injection, we are using the <property> tag as
per properties mentioned in the configuration file .we can use
<p:property-name="property-value"/>
<p:property-name-ref="property-value"/>

instead of property tag which is a short form for specifying the property tag.

For this mention the XML namespace in config file.


xmlns:p=http://www.springframework.org/schema/p

2.c-namespace

To provide the Constructor injection ,<constructor-arg name="" value="" />


we an use the c-namespace
<bean name="beanname" class="" c:constructor-param="value"/>
<bean name="beanname" class="" c:constructor-param-ref="value"/>

Xml Namespace
-------
xmlns:c=http://www.springframework.org/schema/c

#################################################
Constructor injection Features :----
1.If we provide the setter dependency injection ,and constructor dependency
injecttion , setter properties will override the constructor properties.
beacuse setters will be called after creation of objects so properties will
be overriden.

2.Constructor Injection cannot provide the circular dependency injection while


setter injection can provide it..

Circular dependency injection is injecting one obejct of class ONE into another
property of other bean property
----------------Setter circular dependency injection----------------Its possible
bcoz obejcts of each bean are created ,after which APContext assign values to each
ref-property

<bean id="one" class="ONE">


<property ref="secondId"/>
</bean>
<bean id ="secondId" class="Second">
<property ref="oneId"/>
</bean>
---------------------------------------------------------------------

----------------Constructor circular dependency injection----------------


Its NOT possible bcoz objects of each bean are not created since Constructor
requires some fromal parameters to instantiate the object

<bean id="one" class="ONE">


<constructor-arg ref="secondId"/>
</bean>
<bean id ="secondId" class="Second">
<constructor-arg ref="oneId"/>
</bean>
----------------------------------------------------------------------
3.Setter method dependency injection will make the Bean "mutable" while
Constructor injection will make the Bean "immutable"
4.Constructor dependency injection gives injection guarantee , while setter method
injection doesn't give guarantee if dependencies are injected.

####################################################
################AUTOWIRING#########################NOTE: -- Autowiring only works
for User defined References not primitive data type
Till now, we have injected dependent properties using <property> , <constructor-
arg /> tags , in which primitive data type dependeniies are injected using
<value> tag while user defined dependencies are injected using ref attribute or
<ref bean="Class" / > tag . in Bean Configuration file.

So in order to inject properties automatically by ApplicationContext into


respective beans , AUTOWIRING feature is used in which there is no need of
mentioning the <property> , <ref> tags

Ways to manage Autowiring


1.Xml Based Autowiring
2.Annotation Based Autowiring
3.Auto-discovery(stereo Types)
4.java Based Autowiring

Xml Based Autowiring types:----


<bean id="id" class=Class" autowire="<no><byType> <byName> <constructor>" >
1.no (default no autowiring)
2.byName (injecting properties by same name of property)
3.byType (inejcting properties by type of depedency)
4.by constructor ( byType)

#################################################
Maven : -- --
#################################################
functions of Maven :
Run application
start server
deploy application
perform unit testing
prepare reports and documents
undeployment of applications
stop the server

plugins
----------------
get dependencies-
compilation -
test -
run ----------->Maven <-------pom.xml (project
config,dependency,repos,plugins,resources))
packaging - -------->Application
deploy -
start server -
reports -
-
----------------

Project Object Model (pom.xml)


its heart of Maven.
it will provide all the projectft Build configurations whic are required by
Maven
its an XML file int intial version of Maven , pom file name is
project.xml,later on pom.xml
when we create maven pom.xml file will be created automatically
In Maven ,pom.xml provides following responsibilities
1.Project descritpion
2.REpository
3.Dependency management
4.Project inheritance
5.Build Configurations
6.Build Profiles

Project descriptions:---
it will provide details of project like Project name,version number.packaging
type

pom.xml
-------
<project --->
<!---project description--->
<modelversion >3.4.4</modelversion>--->Maven version 2.x ,3.x
<groupId>com.config.dao</groupId> ---is an unique id for our comp
<artifactId>iciic.accounts</artifactId>--->Application name
<description>Application for accounting in icici</description>
<packaging>jar,war,ear</packaging>
-----
----->
</project>

2.Repository
---------------
Repo is place is a location in system which will proviide,manage all the
required jar files to our application

Three types of repositories


1.Local repo
2.Central Repo
3.Remote Repo

1.Local Repo :
Its a location in our system,which will be created by mvn command initially.
In our system ,our local repository is existed at C:\Users\LENOVO\.m2\repository
when we requuire jar files in our application then maven will search for
dependencies first in local repository

2.Central Repository
Its default repository in maven , it is existed in internet at a particular URL
Apcache software foundation has provided a serparet central repository in form od
https://repo.maven.apache.org/maven2/

we are able to use third party provided cetral repository in maven


1.https://mvnrepository.com
2.http://repository.jboss.org/nexus/content/groups/public/
if we want to use third party provided repos. in our application then we must
configure in pom.xml

<project>
<repositories>
<repository>
<id>jboss</id>
<name></name>
<url>ihttp://maven.apache.org</url>
</repository>
</repositories>
</project>

3.Remote Repostiry
If not found in Cenral location remote repo is uded.

Dependency Management: --
1.In Maven project,dependency means depedent jar file.
2.Maven is not giving any option to download the required jar file.Maven will
download required jar files and keep them in our application , but we must
specify the dependencies needed in our application

<project>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
</dependencies>
</project>

if we provide Maven dependency as above then maven will search for hibernate
library with name like
http://repo1.maven.org/maven2/org/hibernate/hibernate-core/5.4.2-Final/
Maven is following ""Transitive Dependencies Mechansim " i.e if our dependency
require other dependency then will automatically download that without
explicitly mentioned by dev.

Dependency Scopes: ---


In app. some dependenciea are required at all phases of projects lifecycle like
Compile, test,run ...and oter required only some of phases of the project
lifecycle in order to limit the depdendencies for the lifecycle phases we will
use following Scopes:

6 Scopes:
1.Compile
2.Provided
3.Runtime
4.Test
5.System
6.import

1.Compile: -- its the default scope of Maven ,dependency is available in all


phases(Compile,test,run) of project.
e.g.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
<scope>compile</scope>
</dependency>

2.Provided : dependeny will be available for compilation and testing phase not
for Runtime.

3.Runtime: scope indicates that dependency is not requuired for compilation,but is


for execution.If its the runtime and test class paths ,but not for compile
class path.

4.Test : dependency is not required for normal use of the application ,


and is only available fir test compilation and execution phases .This scope is
not transitive(it will not download dependent jars )
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

5.System :
Dependencies with system are similar to one with scope "Provided" .The only
difference is system depedencies are not retrieved from remote repository.They
are present under projec's subdirectory and are refered from there.

6.Import :
its available in Maven 2.0.9 or later.
import scope is only supported on a dependency of type pom in file dependency
Mnagament section.It indicates the dependency to be replaced with the

4)Project Inheritance :
InMaven based apps. its possible to inherit Configuration from one pom file to
another pom file inorder to avoid configuration redundancy .

To declare parent pom , we have to use "pom" as value to <packaging> tag in parent
pom file.

e.g. :

<project>
<modelVersion>4.0.0</modelVersion>
<groupId>parent-pom</groupId>
<artifactId>parent-pom</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>

If we want to inherot parent pom configuration details into a particular child


pom then we have to configure parent pom in child pom.

<parent>
<groupId>com.p</groupId>
<artifactId>my-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
</parent>

Note : In Java java.lang.Object class is common and default super class for
every java class inorder to provide 11 common default methods to each ad every
java class . similarly there is a common and default super pom file is existed
in maven inorder to provide all common configurations and settings to the child
pom file.

5)Build Configuration :
In Maven , Buiild Configuration is mainly for plugin configuration ,resources
configurations which are required in Maven projects.

Maven is colection of plugins , where plugins are used to perform the actions like
creating jar files , creating war files. compile source code , executig unit
test code ,create project documentation ,
Maven is having "Plugin Execution Framework " at its heart inorder to execute all
plugins.
In Maven there are two types of plugins:
1.Build plugins
2.Reporting Plugins

1.Build plugins: these plugins are executed during the build and they should
be configured in the <build> element from POM.

e.g.

1.clean : its used when you wat to remove files generated at build time in a
project's directory
2.Compiler : Compiles java source code.
3.Deploy : it can be used to store artifacts in remote repo. while deploying the
app. inorder to share to other projects.
4.install : itcan be used ot install artifacts into local repo.
5.Resources : will include all the project resources in output directoyr while
creating JAR files.
6.Ear : create .ear file from project
7.jar : crate .jar file of prjcts
8.war: create .war file of current project
9.rar : create .rar file from current project/

6)Build Profiles:
In general , profiles are used to customize the build lifecycle for different
environment like development ,testing,

<profiles>

where each and every profile has its own id.it can be used to acces the repective
environment or profile

In src/main/resources/db.properties
jdbc.connection.url = ${jdbc.connection.url}

if we provide the abive setups like above then at compilation time, the
respective jdbc url will be injected into db.properties file dependeing on the
target environment .Use following command on command prompt inorder to compile
the project.

C:/apps>mvn compile
here "jdbc.connection.profile" property will take
"jdbc:oracle:thin@localhost:1521:xe" value

AOP :- Aspect Oriented Programming :


--------------------------------
Intro :

public class Transaction{


public void deposit(){
--Deposit logic
--Authentication
--Logging
--Transact

public void withdraw(){


-- withdraw logic
--Authentication
--Logging
--Transact
}

public void transfer(){


--tranfer logic
--Authentication
--Logging
--Transact

}
}

if we're gonna use above style of implementation then we are able to get the
following benefits:
1.its very difficult to modify the services logic.Any change would affect all
other classses
2.it will not provide the shareability
3.It will not provide the code resuability
4.It will provide the tightly coupled design.(Business logic and services are not
independent .. both are mixed with each other)

To overcome the above problems we have to use Aspect Orientation:-


-----------------------------------------------------------------------
AOP is not a programming language.It is methodology or a paradigm.It wil be
applied on Object oriented Programming on order to get the loosely coupled
design and in order to improve the code resuability and shareability

i.The basic idea is to separate Business logic from Services


ii.Declare each service as an aspect and inject these services into bussiness
logic in the respective location by using the dependency injection

class Bank_transaction{ Aspect

public void deposit(){


--deposit logic-- <-----inject Service to deposit | Logging service |
Authentication service | TransactionService |
}

public void withdraw(){


--withdraw logic-- <-----inject Service to withdraw
}

public void transfer(){


--wtransfer logic-- <-----inject Service to transfer
}
}

AOP Advantages:-
------------------
1.In Enterprise App. Business compoments look very clean and having only
business implementation statements.
2.All services are implemented at common place helping code maintenance.
3.We can make changes at common place so that changes are reflected at all places
where ever services are being used at bussiness logic sites.

AOP vendors:-
-------------
1.AspectJ
2.Spring Aop
3.JBOSS Aop

Spring framework provides following implementations:


-----------------------------------------------------
1.Schema Based implementation
2.AspectJ
i.DEcalratice Based Approach
ii.Annotation Based Approach

AOP Terminologies used for implementing AOP:-


----------------------------------------------
1.Aspect
2.Advice
3.JoinPoint
4.PointCut
5.Target
6.Proxy
7.Weaving
8.Introduction

bm1 : logging |
bm2 : logging,Transaction ,security | __________Proxy
____________________________
bm3 : logging, transaction .security | <------- Weaving -----------> |
Business Comp Advice | Aspect
| [Target object] +
|
| void bm1(){
|
--logging---
LoggingImpl <------------logging
}
JoinPoints(JP) void bm2(){
TransactionImpl<--------Transaction
--logging
--transaction
--security
}
PointCuts(PC) void bm3(){
SecurtiImpl<----------security

--logging

--transaction

--security
}

1.Aspect :
An Aspect is the service or concern that we wanna implement in application .
like logging,transactions , Security

2.Advice :
An Advice is the actual implementation of the aspect.Aspect is the concept while
Advice is the actual implementation of the concept.

3.Join Point :
A join point is the poijt int he application wherethe aspect can be applied.
it could be before/after execution of the method,before throwing an
exception,before/after modifying an instance variable etc.

4.PointCut:
PointCut tell on which joinpoints the aspect will be applied. An advice is
associated with a pointcut expression and is aplpied to joinpoint which matches
the pointcut exprression

5.Target :
Target is a business component class which is being advised.

6.Proxy:
Proxy is the object which is created by framework after applying the advice
on the target obejct.

Proxy = target + advice(s)

7.Weaving:
Weaving is the process of applying the aspect on the target object to produce
the proxy object.Weaving can be done at compile time/runtime or class loading
time.Spring AOP supports weaving at runtime.

8.Introduction:
An introduction allows adding new methods or attributes to existing classes.The
new methods and instance variables can be introduced to existing classes
without having to change them ,giving them new state and behaviour.

Advices in Spring:
---------------------
Advice is the implementation of Aspect.An advice provides the code of
implementation of service or Aspect.As an example logging service, logging is an
aspect and Advice denotes the implementation of Log4j.

In general , all the code of advices will not included in business methods at
compile time ,these services will be inclued at runtime.

Various Spring Advices


-----------------------

1.Before Advice
2.After advice
3.After-returning
4.After-throwing
5.Around-Advice

1.Before Advice :
i.Before Advice contains service/Aspect implementation .it will be executed
before executing the repective business method.
ii.To represent BeforeAdvice Spring framework has provided a predefined
interface "org.springframework.aop.MethodBeforeAdvice"
iii. For implementing Before advice we have to define a user defined class .
it must implement MethodBeforeAdvice interface and we must provide the
implmentation of methods of MethodBeforeAdvic interface
a)public void before(Method m,Object [] Business_method , Object
target)throws Exception : where java.lang.reflect.Method parameter providdde
metadata of Business method to which before Advice is applied.where Object[]
array is providing business method parameter values in the form of
Objects.where object is target object

Note: the services which are implemented in before() method are executed
before executing the business logic.

Example :

public class BeforeAdviceImpl implements MethodBeforeAdvice {

)public void before(Method m,Object [] Business_method , Object target)throws


Exception {
------Service logic----
}

2.After Advice[After returning Advice]


--------------------------------------
its is same as before advice ,but this advice contains services which are
applied after ecompletion of business method logic.

To create an AfterAdvice implement


Interface: org.springframework.aop.AfterReturningAdvice

Method:
public void afterReturning(Object returnValue.Object[] args, Object
target)throws Exception
i.Object returnvalue is the return value of the business method of Object type.
ii.args = business method parameters in form of Object[]
iii.Object is target Object.
public class AfterReturningAdviceImpl implements AfterReturningAdvice {

public void afterReturning(Object returnValue,Object [] Business_method_args ,


Object target)throws Exception {
------Service logic----
}

Note: In Schema based impl. After and AfterReturning Advice are same .In annotation
approach are different

4.After Throwing or Throws Advice:


---------------------------------
This advice is executed when the business logic throws an execption .
Interface: org.springframework.aop.ThrowsAdvice
Method:
public void afterThrowing(Method,args,target] , ThrowableSubclass)
examples:
public void afterThrowing(Exception e)
public void afterThrowing(RemoteException)
public vooid afterThrowing(Method method_metadata, Object[] business_method_args,
Object target,Exception ex)
public void afterThrowing(Method method_metadata, Object[] args , Object
target ,ServletException exception)

Example:
public class ThrowsAdviceImpl implements ThrowsAdvice{

public void afterThrowing(Method business_method_metadata , Object []


Business_method_args , Object target , Exception ex)throws Exception {
------Service logic----
}

5.Around Advice:
Around Advice will be executed before and after executing of Business
logic.combination of Before and After advice.Its from Open Source implementation
called AOP Alliance not given by spring framework.

Interface:
org.springframework.intercept.MethodInterceptor
Methods:
public Object invoke(MethodInvocation mi) throws Throwable
In Around Advice , we will implement before and After Advice in invoke()
method, in invoke() method will pprovide before advice logic before proceed()
method and we wil provide After Advice logic after calling proceed() method.

Example:
public class AroundAdviceImpl implements MethodInterceptor{
public Object invoke(MethodInvocation mi)throws Throwable{
//Before logic
Object o = mi.proceed();
//After logic
return ob;
}

AspectJ:---
------------
AspectJ is well known in AOP language.It provides specialized syntax to express
concerns.It also provides tools to add a concern into system and enable cross
cutting concerns and modularization ,such as logging, error checking and
handling and so on.

Spring is supporting AspectJ in following 2 ways.


1.Declarative approach.
2.@AspectJ annotation style approach

In AspectJ approach we will use AspectJ namespace tags inorder tp declare


aspects ,advices , pointcuts

In declarative configuration approaach .all aspect declarations are placed


under <aop:config/> tag

To use AOP namespace tags ,we need to import the spring-aop schema.

applicationContext.xml

<beans>
<aop:config>

<aop:config/>
</beans>

Note : The aop config will contain all the aspect configuration and all
specific method -related configuration ,such as around , pointcut, asn so on .
1.Declaring Aspects:
To declare aspects by using AspectJ namespace tags we have to use
the follwoing tags
<aop:config>
<aop:aspect id="" ref="" >
--
</aop:aspect>
</aop:config>

where id attribute will take aspect id value


where ref attribute will take identity of class which has declared in
the configuration file by using <bean> tag in out side of <aop:aspect>
tag

ex:
<beans>
<aop:config>
<aop:aspect id="loggingaspectn" red ="loggingAspectBean" >
--
</aop:aspect>
</aop:config>

</beans>
2.declaring PointCuts
A pointcut helps in determining the join points to be executed with different
advices .To declare pointcuts we have to use the follwing tags in
configuration file

<beans>
<aop:config>
<aop:aspect id="loggingaspectn" red ="loggingAspectBean" >
<aop:pointcut id="--" expression="--" />>
--
</aop:aspect>
</aop:config>

</beans>

i.where id attribute in <aop:pointcut> tag will take identity to the


pointcut
ii.where expression tag in <aop:pointcut> will take AspectJ expression to
define expression for the business methods which are reqiured Advices .
ii. where expression attribute will take "execution" function with an
expression

ex:--
<aop:pointcut id = "businessService" expression
="execution(*com.ducat.service.*.*(..))" />

In the above code ,expression will represent all java methods with any type
of return type

<beans>
<aop:config>
<aop:aspect id="loggingaspect" red ="loggingAspectBean" >
<aop:pointcut id = "businessService" expression
="execution(*com.ducat.service.EmployeeService.*(..))" />
--
</aop:aspect>
</aop:config>
</beans>

<bean id = "loggingAspectBean"
class="com.ducat.aspect.EmployeeCRUDLoggingAspect" />

Examples on Pointcut expression : --


------------------------------------
1.execution("com.ducat.service.EmployeeService.*(..)")
The above expression matches all of the methods declared in he
EmployeeService interface
The above expression matches with any modifier (public ,protected ,private )and
any return type
The two dots in the argument list match any number of arguments

2.execution("EmployeeService.*(..)"))
the above Expression matches all methods of EmployeeSerivve interface which
ae existed in the present pacckage with anu type of access modifier and
any type of return type

3.execution(public * EmployeeService.*(..))
the above expression matcheds all public methods of EmployeeSerive interface
with any return type.

4.execution(public Employee EmployeeService.*(..))


The above expression matches all public methods of EmployeeService
interface with return type

5.execution(public Employee EmployeeService.*(Employee,..))


Above expression matches all methods of EmployeeService interface with Employee
return type and first parameter as Employee

6.execution(public Employee EmployeeService.*(Employee,Integer))


The above expression matches all methods with all public methods of
employeeService interface with Employee and Integer as parameters and
Employee as return type

Declaring Advices:--
------------------------
Spring AspectJ is supporting the following five advices.

<aop:before> id is applied before calling the actual business logic


method .
<aop:after> it is called after calling the actual business logic method
<aop:after-returning> its applied after calling the actual business logic
method . its can be used to intercept the return value in advice
<aop:around> it is applied before and after calling the actual business
logic method.
<aop:after-throwing> its applied if actual business logic throws exception

All the above advice tags contains "method" and "pointcut-ref" attriutes,
where "method" attribute wil take advice method and "pointcut-ref" wwill
take pointcut references which we declared in configuration file

<aop:config>
<aop:pointcut id="logginhOperation" expression
="execution("com.ducat.service.EmployeeService.*(..)")"/>

<!--Spring aop aspect-->


<aop:aspect id="loggingAspect" ref="loggingAspectBean">

<!-- Spring Aop Advices-- >


<aop:before pointcut-ref="loggingOperation" method="logBefore"/>
<aop:after pointcut-ref="loggingOperation" method="logAfter"/>
<aop:aspect>
</aop:config>

<bean id="loggingAspectBean" class="com.ducat.aspect.EmployeeCRUDLoggingAspect"/>

<!-- target object-->>


<bean id="employeeManager" class ="com.ducat.service.EmployeeServiceImpl" />
</beans>

MVC :---
----------
1.Standalone Application:
--single user Env.
--Less Shareability.
--No Server Env.

2.Distributed Applications
--Multi user Env.
--More Sharability
--Server Env.
1.web based Distributed appl.
2.Remote Based Distributed appl.

Q) what r the differencce b/w Web based Distributed Aplications and Remote
Distributed Applications.

web appl.(servlet,JSPs) Distributed appl.(RMI,CORBA,EJBs,Web


services)

User,client-------request--------->{ICICI Server}----(Internet Cloud)-------> {HDFC


Server}
<-----response-------- <------- --------

#MVC Model 1 architecture:----(Front Controller)


==================================

Java Beans ----------->Databases


^ <-----------
|
Client -----request----->{Server}View/Controller (JSPs)
<---response----

#MVC Model 2 architecture:----


=====================================

{Server}

Client -----request----->|Controller(Servlets)|
^ |
| |
| |
| >
|response--------|View(HTML,JSPs)|---------------------->|Model(Java
Beans,Hibernate, JPA,JDBC)|--------->Database
<----------------------
<--------

The main intentions of Spring Web MVC module is to prepare web


applications with MVC design patterns.
Q) what is use of Spring web MVC if we have Struts framework
Ans:--
1.Struts is web framewaork , it provides good environment to preapre web
applications.

Spring framework is an application framework can be used to prepare web


based , standalone applications, distributed apps.

2.Struts framework is mainly MVC based framework it is mainly using MVC and
MVC corelated MVC design ppatterns,

In Spring framework only web module is able to use MVC design patterns

3.Struts is heavyweight framework..


Spring framework is light weight framework.

4.Struts framework is able tp provide very tightly coupled design for


apps.
Spring framework provides loose coupling b/w Model,View and Controller logic.

5.Struts framework is not able to provide clear separation b/w Controller,


Model, View part.
Spring framework is able to provide clear separation b/w Controller, Model,
View part.

6.Struts is very API dependent ,its very difficult to perform debugging and
testing.
Spring is less API dependent , easy to debug and test Spring apps.

7.Struts is not able to provide good environment to integrate other


technology applications like JDBC, Hibernate .EJBs

Spring provides a nice environment to integrate with other techs. like


Hibernate , JDBC.

8.Struts is able to use only HTML , JSPs( basic view related techs . to
prepare view part )

Spring provides very good environment to use view related techs like HTML
, JSPs,velocity, Freemarker

9.Struts are not having AOP implementations to provide loosly coupled design.
Spring is having AOP implementations to provide loosly coupled design.

10.Struts is not modularized /layered framework.


Spring is layered /modularized framework.

11.Struts is said to be invasive .In Struts we used to extend Action classes and
ActionForm classes.It forces the programmer that, te programmer must extend from
the base class provided by struts API.
Spring framework is not invasive means it doesnt force a programmer to extend
or implement their classes from any predefined class or interface given by
Spring APi/

12. Struts framework is able to provide very good tag library.


Spring framework is not providing any tag library to build view part.

13. Struts is not providing any support for Transaction Management and
Messaging support.
Spring provides Messaggging and Transanction support.
##########################################
Q) To prepare MVC based application we have JSF what is the need of Spriing
Web MVC module.
1.JSF is a we framework . its able to provide environment to prepare web
applications only.

Spring framework is able to provide environment for all standalone as well as


web applications ,distributed apps..

2.JSF is component based framework .for every view , JSF will create a
Component Tree inorder to manage data.

form.jsp

Username : abc |Component Tree|


password : *** form
Qualification : Btech / / \ \
MSc
Bsc i:username tf:abc cb: Bsc cb:MSc

Submit
Bean: username=abc , upwd=123 ,
uqual=Bsc,Msc (Spring data is sent in form of Bean Object while JSF send in
Component tree as above)

Spring framework is not component based framework . It will use beans to


manage Form data..

3.JSF is view layered framework . it will focus on view layer.


Spring is not view layered framework .it will focus on all layers of
Enterprise apps.

4. JSF is having very good convertors , Validations and Rendering mechanism.

Spring is not having good convertors , Validations and rendering mechanism.

5. JSF is having inbuilt AJAX support.


Spring is not having inbuilt AJAX support.

6.JSF is not having MiddleWare Services support like Transactions , Messaging.


Spring is having good suppport of Transactions , Messaging.

7.JSF is not having any integration environment to integrate other


technologies apps. like JDBC, EJBs RMI
Spring is having very good env. to integrate other techs. like JDBC,

8.JSF is not having any security implementations


Spring provides very good support for Security with spring security module.

Spring Web MVC features.


---------------------------------
1.Spring Web MVC contains no. of components like controller, Validator ,
command object, form object, model object, DispatcerServlet ,handler mapping ,
view resolver, and so on.
Each and every component has its own role and responsibility.
2.Spring allows powerfull configuration of framework and application classees
as java Beans. This configuration includes easy navigation across contexts
,such as from web controllers to busines objects and validators .
3.Spring framework is allowing Command Object and Form objects to reuse
Business Code instead of extending Frameworks provided API libraries.
4.Spring Web MVC is providing very good Data Binding mechanism, Data
Validations for web applications.
5.Spring Web MVC is providing Customizable handler mapping and view resolution.
6.Spring MVC module is more flexible model transfer .Model transfer with a
name/value Map supports easy integration with any view technology.
7.Spring web MVC provides customizable locale and theme resolutions, ,support
for JSPs with or without Spring tag library, support for JSTL ,Support for velocity
without the need for extra bridges and so on.
8.Sring Web MVC allows all JSP supported Tag libraries like JSTL tag library.

Spring Web MVC Components:


-------------------------------
1.View
2.web.xml
3.DispatcherServlet
4.Handlermapping
5.Controller Component
6.Command Object
7.View Resolver
8.Spring Configuration file

MVC Flow:---
-------------------------------

----------Request-------->|Controller|
/ \
/ \
<----Response------| View|<------>|Model|

Struts Flow:--
---------
------------------------
<form action="login.do">|
loginForm.html |
| > login<--> LoginAction<-->
LoginActionForm<---> struts-config.xml
uname:______ | | success<-------
>success.html
upwd :______ | | failure<-------
>failure.html
| |
Login Button ------------|-----Request---->|ActionServlet|------------>LoginAction
------------------------- | AcationForward
execute(-,-,-) {---return new ActionForwardF("success");}
|
|Login was successfull!|<-----Response-----|success.html| |failure.html|

_______________________________________________________
Struts Spring MVC
--------------------------------------------------------
View----------------------------->View
ActionServlet-------------------->DispatcherServlet
ActionForm----------------------->Command Class
Action--------------------------->Controller Component
struts-config.xml---------------->HandlerMapping, ViewResolver

Spring MVC FloW


-----------------------

>Handler Mapping
|
|
<
Client -----Request-------> Front Controller(DispatcherServelt)<-------
>Controller(return new ModelAndView(Map<> , "success"))------>Command class Object
<----Response------ < <
| |
| |
| |
> >
View ViewResolver

From the above diagram :---


1.Submitting the client request to Server side web application, where
DispatcherServlet will receive the request.
2.DispatcherServlet will interact with Handlermapping to get the Controller
name and location
3.Handlermapping will return the controller name and location.
4.DispatcherServlet will recognize the name and location of the Controller
class ans peerform the instantiation of the Controller class.
5.Depending on the controller ,Form data will be stored in Command object
and that Command Object data will be used in Controller class.
6.After executing the Businsess logic , Controller class will return the
ModelView Object which contains logical name of the view in View Object and
Model Object is a Map object contains Model Objejct inorder to use that data
in View Part..
7.Dispatcherservlet will interact with ViewResolver inorder to get the name
and location of the View page.
8.View Resolver will return the View Obejct with the name and location of the
View page.
9.DispatcherServlet will interact with View part with Model part inorder to
prepare response.
10.View part will prepare the response and submitting the response to
DispatcherServlet View page.
8.View Resolver will return the View Obejct with the name and location of the
View page.
9.DispatcherServlet will interact with View part with Model part inorder to
prepare response.
10.View part will prepare the response and submitting the response to
DispatcherServlet..
11.DispatcherServlet will generate the response back to Client browser.

View:--
-----------
1.To submit data in forms.
2.To interact with users.
3.To request GET ,POST, PUT, HEAD requests to web .

Two parts :
1.Informational View
ii.to display messages to users, status of web server
ii.t will not include forms. only smple data.

web.xml(Deployment Descriptor)
1.Metadata about the web app required by web container .

1.welcome file.
2.Context paramters.
3.Servlet config.
4.Filters.

dispatcherServlet.servlet.xml
Where DispatcherServlet class must be configured with its fully qualified
name inorder to activate FrontContoller .
ex. <servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-
class>

where initialization parameter are required to create the Framework


related objects like HandlerMapping ,HandlerAdapter , ViewResolver .
Note:-- The default location name of Spring Configuration file is under
WEB-INF folder with servlet_logicall_name-servlet.xml" but we can change
acording to us by mentiuoning in "contextConfigLocation" initilization
paramter in DispatchersServlet config.

ex.
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/mysqocnfig.xml</param-value>
`</init-param>

where URL pattern defication is required in each and every servlet in web
app. In general in web app. we define the URL pattern for the servlet
in following ways.
1.Exact Match method.
2.Directory match method
3.Extension match metod

from above method URL pattern definition , DispatcherServlet required to


use either directory method [/*] or Extension match method [*.do] inorder to
trap all th requests frrom client to DispatcherServlet .

web.xml
<web-app>

<servlet>
<servlet-name>dispactherServlet<servlet-name>
<serlvet-class>org.springframework.web.servlet.DispactherServlet</servlet-
name>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<url-pattern> *.do</url-pattern> or
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

3.DispatcherSerlvet : --
main functions of front controller :

1.getting request from Clients.


2.identifying the respective Model component or Business component which
includes business logic.
3.Exceuting the busiiness logic which is existed in Business component.
4.Identifiyng the repective View part inorder ot generate te response.
5.Forwarding the request to view part inorder to generate the dynamic
respnse.

In spring wee mvc module , DispatcherServlet is actng as front controller


provided by Spring framework in form of
"org.sprinframework.web.serlet.DispatcherServlet"

Servlet(I)
>
|
GenericServlet(C)
>
|
HttpServlet(C)
>
|
HttpServletBean(C)------------(ViewResolver ,HandlerMapping , ThemeResolver ,
LocaleResolver)(classes)
>
|
FrameWorkServlet(C)------------>WebApplicationContext (I) ,
XmlWebApplicationContext(C)
>
|
DispatcherServlet(C)

1.where HttpServletBean is the first Spring-aware class in the hierarchy


.it injects the bean properties using the Servlet init -param values
received from web.xml or from webApplicationInitializer
2.where Frameworkservlet integrates the Servet functionality with a web
application contedxt , implementing the ApplicationContextAware
interface . But its the able to create the web appliaction context in
it.
3.where Dispatcherservlet will perform the following actions in Spring
web MVC applications inorder yo process the requests.
4.From above diagram :
1.When we start the server , container will perform following actions .

client ---DS loading->DS inst->Dispatcher vector -> WAC loading->WAC


inst->WAC initialization --> ds-servlet.xml
------ |
| |RF| | ------------------
|------>| web.xml ---> |Dispatcherservlet|<===> |HandlerMapping|
Interceptors
----- <----- | DS<->.*do | | ||
| | ModelAndView |<===> |HandlerAdapter| <===> ||
<============> | Handler/Controller|
| | object | ||
| | | ||
| | view |<===> |ViewResolver| ||
-----
|<------------ | |<----------------------------||
<-------| View |
| |
|-------------------------------------->| |
| ------------------
------

From above diagram :


1. when we start server ,container will perform follwoing operations .
a. Container will recognize all the web applications , which exits under
webapps folder.
b.container will deploy all the web apps under server page.
c.conatiner will craete separate ServletContext object for each and evry
web application which we deployed.

2.while we deploy web application , container will perform the foollwing


operations
a.Container will recognize web.xml file under WEB-INF folder.
b.Container will perform laoding ,parsing , reading of web.xml file
c. while parsing web.xml file container will recorgnize the load-on-
startup configuration under Dispatcherservlet Config.
d. With the load-on-startup container will search for DispatcherServlet
under classes folder . if its not existed conatiner will search for
DispatcherServlet under web application folder.
e.When DispatcherServlet identifies then container will pperform
DispatcherServlet instantiation and inialization at the time of server
startup or at the time of web app. deployement.
3. As part of Dispatcherservlet initialization ,DispatcherServlet will
perform the following actions,
a. DispatacherServlet will recognize the WebApplicationContext
implementation class and perform WebApplicationContext loading ,
instantiation , initialization .
b. As part of WebApplicationContext initialization ,
webApplicationContext will recognize the Struts config. file under WEB-INF
folder with the file name "Servlet_Name"-servlet.xml WebApplicationContext
will perform the Spring Config. loading ,parsing , reading , the content
of Configuration object,
4.After getting all the config. details from the spring config file into
Configuration object . WebApplciationContext container will create bean
objects which we configured in spring config. file.
d.After getting all the bean objects .WebApplciationContext will create
ibjects of HandlerMapping , ViewResolver , ThemeResolver , LocaleResolver etc.
as part of WebApplicatipnContext initialization.

4.When we submit request from client to Server . then protocol , will


take request and perform the following actions.
1. Protocol will establish connection b/w client and server on the basis
of Server IP address and port.
2.Protocol wil create requeest format conatinging the headers , body ,
where header will manage client metadata and body will manager Request
data received from Client browser.
3.Protocol will carry request to server and forward to web Container.
5. When request is coming to container then web container will take URL
pattern value from request format nad container is trying to compare the
URL pattern of the DispatcherServlet which we configured in web.xml file
, where if URL pattern is matched with Dispatcher Servlet URL, then
Container will forward the request to DispatcherServlet.
6.When Request is coming to DS , then DS wil perform follwing actions,
a. DS will keep all the framework objects like HandlerMapping ,
HandlerAdaptor , ViewResolver , ThemeResolver , LocaleResolver in reuqest
scope in order to make available to the Handler and View part.
b.DS will interact with HandlerMapping object to get the Handlera and
controller objects by getting getHandler() method.
c. when DS call getHandler() on HandlerMapping Object , HandlerMapping will
recognize the respective Handler object , and its configured interceptors ,
then HandlerMapping will arrange all the interceptors before Handler and
return HandlerExecutionChain object which contains the Hanlder Obect and a
set of interceptors.

Note:Interceptors are like Filters in Servlet . which are used to do pre-


processing and post processing of web-resources.
d. After getting the HandlerExecutionChain obejct, DS will use
HanlderAdaptor object to access Hanlder by using handle() method. where
HandlerAdaptor will execute all the interceptors inorder to perform pre-
processing activites by calling the preHandle() method.
e. After executing the interceptors , handlerAdaptor will access business
logic which is included in Handler or controller component..
f.. After executing the Business logic in Hanlder class, Handler will
return the ModelAndView object to HandlerAdaptor by executing all the
interceptors in reverse order to provide the post-processing activities by
executing the postHandle() method wherr HandlerAdaptor will send the
received ModelAndView object to DS.

g.After getting the ModelAndView object ,DS will interact with the
ViewResolver inorder to identify the view JSP page url on the basis of
View name.
h.When View is identified in web applciation then DS will execute the
corrresponding view page by geting the data from Mode part of ModelAndVoew
object and DS wil prepare response for client.
h.When DS wil prepare response . DS will send response to client where
protocol wil take following actions.

a. Protocol will prepare response format contains Header part and Body
part wher Header part is able to manage the headers data like response
size , type of response and body part is able to manage theb actual
dynamic response.
b. Protocol will carry response format to client , where client browser
will display the generated response,
c. when response is received at the client browser the protocol willl
destroy thhe connection b/w client and server.
d. when we shutdown the server or when we undeploy the web application
then container will perform the DS deinstantiation with this alll the
spring.
Framework obejcts like HandlerMapping , ViewResolver , HandlerAdaptor are
destroyed.

Вам также может понравиться