Академический Документы
Профессиональный Документы
Культура Документы
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
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
Class c= Class.forName("com.core.MyBean");
#2.Bean Instantiation
c.newInstance();
#3.Bean Initialization
#4.Bean DeInstantiation
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
###Destruction Order
##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
<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.
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 .
1.Constructor DI
<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.
2.c-namespace
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.
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
####################################################
################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.
#################################################
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 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
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/
<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.
6 Scopes:
1.Compile
2.Provided
3.Runtime
4.Test
5.System
6.import
2.Provided : dependeny will be available for compilation and testing phase not
for Runtime.
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>
<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
}
}
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)
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
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.
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.
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 :
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 {
Note: In Schema based impl. After and AfterReturning Advice are same .In annotation
approach are different
Example:
public class ThrowsAdviceImpl implements ThrowsAdvice{
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.
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>
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>
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" />
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.
Declaring Advices:--
------------------------
Spring AspectJ is supporting the following five advices.
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.*(..)")"/>
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.
{Server}
Client -----request----->|Controller(Servlets)|
^ |
| |
| |
| >
|response--------|View(HTML,JSPs)|---------------------->|Model(Java
Beans,Hibernate, JPA,JDBC)|--------->Database
<----------------------
<--------
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
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.
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.
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/
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.
2.JSF is component based framework .for every view , JSF will create a
Component Tree inorder to manage data.
form.jsp
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)
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
>Handler Mapping
|
|
<
Client -----Request-------> Front Controller(DispatcherServelt)<-------
>Controller(return new ModelAndView(Map<> , "success"))------>Command class Object
<----Response------ < <
| |
| |
| |
> >
View ViewResolver
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>
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
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 :
Servlet(I)
>
|
GenericServlet(C)
>
|
HttpServlet(C)
>
|
HttpServletBean(C)------------(ViewResolver ,HandlerMapping , ThemeResolver ,
LocaleResolver)(classes)
>
|
FrameWorkServlet(C)------------>WebApplicationContext (I) ,
XmlWebApplicationContext(C)
>
|
DispatcherServlet(C)
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.