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

Spring:

Spring is a lightweight inversion of control and aspect-oriented container


framework.
Advantages:

Lightweight spring is lightweight when it comes to size and


transparency. The basic version of spring framework is around 1MB. And
the processing overhead is also very negligible.
Inversion of control (IoC) Loose coupling is achieved in spring using
the technique Inversion of Control. The objects give their dependencies
instead of creating or looking for dependent objects.

Aspect oriented (AOP) Spring supports Aspect oriented programming


and enables cohesive development by separating application business
logic from system services.

Container Spring contains and manages the life cycle and configuration
of application objects.

Framework - Spring provides most of the intra functionality leaving rest of


the coding to the developer.

Spring framework modules:

The Core container module


Application context module

AOP module (Aspect Oriented Programming)

JDBC abstraction and DAO module

O/R mapping integration module (Object/Relational)

Web module

MVC framework module

Structure of Spring framework:

Core container module:


This module is provides the fundamental functionality of the spring
framework. In this module BeanFactory is the heart of any spring-based
application. The entire framework was built on the top of this module. This
module makes the spring container.
Application context module:
The Application context module makes spring a framework. This module
extends the concept of BeanFactory, providing support for internationalization
(I18N) messages, application lifecycle events, and validation. This module
also supplies many enterprise services such JNDI access, EJB integration,
remoting, and scheduling. It also provides support to other framework.
AOP module:
The AOP module is used for developing aspects for our Spring-enabled
application. Much of the support has been provided by the AOP Alliance in
order to ensure the interoperability between Spring and other AOP
frameworks. This module also introduces metadata programming to Spring.
Using Springs metadata support, we will be able to add annotations to our
source code that instruct Spring on where and how to apply aspects.
JDBC abstraction and DAO module:
Using this module we can keep up the database code clean and simple, and
prevent problems that result from a failure to close database resources. A
new layer of meaningful exceptions on top of the error messages given by
several database servers is bought in this module. In addition, this module

uses Springs AOP module to provide transaction management services for


objects in a Spring application.
Object/relational mapping integration module:
Spring also supports for using of an object/relational mapping (ORM) tool
over straight JDBC by providing the ORM module. Spring provide support to
tie into several popular ORM frameworks, including Hibernate, JDO, and
iBATIS SQL Maps. Springs transaction management supports each of these
ORM frameworks as well as JDBC.
Web module:
This module is built on the application context module, providing a context
that is appropriate for web-based applications. This module also contains
support for several web-oriented tasks such as transparently handling
multipart requests for file uploads and programmatic binding of request
parameters to your business objects. It also contains integration support with
Jakarta Struts.
MVC Framework:
Spring comes with a full-featured MVC framework for building web
applications. Although Spring can easily be integrated with other MVC
frameworks, such as Struts, Springs MVC framework uses IoC to provide for
a clean separation of controller logic from business objects. It also allows you
to declaratively bind request parameters to your business objects. It also can
take advantage of any of Springs other services, such as I18N messaging
and validation.
BeanFactory:
A BeanFactory is an implementation of the factory pattern that applies
Inversion of Control to separate the applications configuration and
dependencies from the actual application code.
AOP Alliance:
AOP Alliance is an open-source project whose goal is to promote adoption of
AOP and interoperability among different AOP implementations by defining a
common set of interfaces and components.
Spring configuration file:

Spring configuration file is an XML file. This file contains the classes
information and describes how these classes are configured and introduced
to each other.
simple spring application:
These applications are like any Java application. They are made up of several
classes, each performing a specific purpose within the application. But these
classes are configured and introduced to each other through an XML file. This
XML file describes how to configure the classes, known as the Spring
configuration file.
XMLBeanFactory:
BeanFactory has many implementations in Spring. But one of the most
useful one is org.springframework.beans.factory.xml.XmlBeanFactory,
which loads its beans based on the definitions contained in an XML file. To
create an XmlBeanFactory, pass a java.io.InputStream to the constructor.
The InputStream will provide the XML to the factory. For example, the
following code snippet uses a java.io.FileInputStream to provide a bean
definition XML file to XmlBeanFactory.

BeanFactory factory = new XmlBeanFactory(new


FileInputStream("beans.xml"));
To retrieve the bean from a BeanFactory, call the getBean() method by
passing the name of the bean you want to retrieve.
MyBean myBean = (MyBean) factory.getBean("myBean");

ApplicationContext implementations in spring framework:

ClassPathXmlApplicationContext This context loads a context


definition from an XML file located in the class path, treating context
definition files as class path resources.
FileSystemXmlApplicationContext This context loads a context
definition from an XML file in the filesystem.
XmlWebApplicationContext This context loads the context definitions
from an XML file contained within a web application.

Bean lifecycle in Spring framework:


1. The spring container finds the beans definition from the XML file and
instantiates the bean.
2. Using the dependency injection, spring populates all of the properties
as specified in the bean definition.
3. If the bean implements the BeanNameAware interface, the factory
calls setBeanName() passing the beans ID.
4. If the bean implements the BeanFactoryAware interface, the factory
calls setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their
post- ProcessBeforeInitialization() methods will be called.
6. If an init-method is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the
bean, their postProcessAfterInitialization() methods will be called.
Bean wiring:
Combining together beans within the Spring container is known as bean
wiring or wiring. When wiring beans, you should tell the container what beans
are needed and how the container should use dependency injection to tie
them together.
Adding bean in spring application:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="foo" class="com.act.Foo"/>
<bean id="bar" class="com.act.Bar"/>
</beans>

In the bean tag the id attribute specifies the bean name and the class attribute
specifies the fully qualified class name.
Singleton beans and prototype beans:
Beans defined in spring framework are singleton beans. There is an attribute
in bean tag named singleton if specified true then bean becomes singleton
and if set to false then the bean becomes a prototype bean. By default it is set
to true. So, all the beans in spring framework are by default singleton beans.
<beans>
<bean id="bar" class="com.act.Foo" singleton=false/>
</beans>
Beans lifecycle methods:
There are two important bean lifecycle methods. The first one is setup which
is called when the bean is loaded in to the container. The second method is
the teardown method which is called when the bean is unloaded from the
container.
Override beans default lifecycle methods:
The bean tag has two more important attributes with which you can define
your own custom initialization and destroy methods. Here I have shown a
small demonstration. Two new methods fooSetup and fooTeardown are to be
added to your Foo class.
<beans>
<bean id="bar" class="com.act.Foo" init-method=fooSetup
destroy=fooTeardown/>
</beans>
Inner Beans:
When wiring beans, if a bean element is embedded to a property tag directly,
then that bean is said to the Inner Bean. The drawback of this bean is that it
cannot be reused anywhere else.
Types of bean injections:

There are two types of bean injections.


1. By setter
2. By constructor
3. Method Injection (Interface Injection, rarely used)
Auto wiring:
You can wire the beans as you wish. But spring framework also does this
work for you. It can auto wire the related beans together. All you have to do is
just set the autowire attribute of bean tag to an autowire type.
<beans>
<bean id="bar" class="com.act.Foo" Autowire=autowire type/>
</beans>
Different types of Autowiring:
There are four different types by which autowiring can be done.
o
o

byName
byType

constructor

autodetect

Types of events related to Listeners:


There are a lot of events related to ApplicationContext of spring framework.
All the events are subclasses of org.springframework.context.ApplicationEvent. They are

ContextClosedEvent This is fired when the context is closed.


ContextRefreshedEvent This is fired when the context is initialized or
refreshed.

RequestHandledEvent This is fired when the web context handles any


request.

Aspect:
An aspect is the cross-cutting functionality that you are implementing. It is the
aspect of your application you are modularizing. An example of an aspect is

logging. Logging is something that is required throughout an application.


However, because applications tend to be broken down into layers based on
functionality, reusing a logging module through inheritance does not make
sense. However, you can create a logging aspect and apply it throughout your
application using AOP.
Jointpoint:
A joinpoint is a point in the execution of the application where an aspect can
be plugged in. This point could be a method being called, an exception being
thrown, or even a field being modified. These are the points where your
aspects code can be inserted into the normal flow of your application to add
new behavior.
Advice:
Advice is the implementation of an aspect. It is something like telling your
application of a new behavior. Generally, and advice is inserted into an
application at joinpoints.
Pointcut:
A pointcut is something that defines at what joinpoints an advice should be
applied. Advices can be applied at any joinpoint that is supported by the AOP
framework. These Pointcuts allow you to specify where the advice can be
applied.
Introduction in AOP:
An introduction allows the user to add new methods or attributes to an
existing class. This can then be introduced to an existing class without having
to change the structure of the class, but give them the new behavior and
state.
Target:
A target is the class that is being advised. The class can be a third party class
or your own class to which you want to add your own custom behavior. By
using the concepts of AOP, the target class is free to center on its major
concern, unaware to any advice that is being applied.
Proxy:

A proxy is an object that is created after applying advice to a target object.


When you think of client objects the target object and the proxy object are the
same.
Weaving:
The process of applying aspects to a target object to create a new proxy
object is called as Weaving. The aspects are woven into the target object at
the specified joinpoints.
Different points where weaving can be applied:

Compile Time
Classload Time

Runtime

Advice types:

Around : Intercepts the calls to the target method


Before : This is called before the target method is invoked

After : This is called after the target method is returned

Throws : This is called when the target method throws and exception

Around : org.aopalliance.intercept.MethodInterceptor

Before : org.springframework.aop.BeforeAdvice

After : org.springframework.aop.AfterReturningAdvice

Throws : org.springframework.aop.ThrowsAdvice

Different types of AutoProxying:

BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator

Metadata autoproxying

Exception class related to all the exceptions that are thrown in spring
applications:
DataAccessException - org.springframework.dao.DataAccessException

Exceptions thrown by spring DAO classes:


The springs DAO class does not throw any technology related exceptions
such as SQLException. They throw exceptions which are subclasses of
DataAccessException.
DataAccessException:
DataAccessException is a RuntimeException. This is an Unchecked
Exception. The user is not forced to handle these kinds of exceptions.
Configuring bean to get DataSource from JNDI:
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>

DataSource connection pool creation:


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driver">
<value>${db.driver}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>

How JDBC can be used more efficiently in spring framework?


JDBC can be used more efficiently with the help of a template class provided
by spring framework called as JdbcTemplate.
How JdbcTemplate can be used?

With use of Spring JDBC framework the burden of resource management and
error handling is reduced a lot. So it leaves developers to write the statements
and queries to get the data to and from the database.

JdbcTemplate template = new JdbcTemplate(myDataSource);


A simple DAO class looks like this.
public class StudentDaoJdbc implements StudentDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
more..
}

The configuration is shown below.


<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="studentDao" class="StudentDaoJdbc">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>
<bean id="courseDao" class="CourseDaoJdbc">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>

How do you write data to backend in spring using JdbcTemplate?


The JdbcTemplate uses several of these callbacks when writing data to the
database. The usefulness you will find in each of these interfaces will vary.

There are two simple interfaces. One is PreparedStatementCreator and the


other interface is BatchPreparedStatementSetter.
Explain about PreparedStatementCreator?
PreparedStatementCreator is one of the most common used interfaces for
writing data to database. The interface has one method
createPreparedStatement().

PreparedStatement createPreparedStatement(Connection conn)


throws SQLException;

When this interface is implemented, we should create and return a


PreparedStatement from the Connection argument, and the exception
handling is automatically taken care off. When this interface is implemented,
another interface SqlProvider is also implemented which has a method
called getSql() which is used to provide sql strings to JdbcTemplate.
Explain about BatchPreparedStatementSetter?
If the user what to update more than one row at a shot then he can go for
BatchPreparedStatementSetter. This interface provides two methods

setValues(PreparedStatement ps, int i) throws SQLException;


int getBatchSize();

The getBatchSize() tells the JdbcTemplate class how many statements to


create. And this also determines how many times setValues() will be called.
Explain about RowCallbackHandler and why it is used?
In order to navigate through the records we generally go for ResultSet. But
spring provides an interface that handles this entire burden and leaves the
user to decide what to do with each row. The interface provided by spring is
RowCallbackHandler. There is a method processRow() which needs to be
implemented so that it is applicable for each and everyrow.

void processRow(java.sql.ResultSet rs);

Hibernate:
Hibernate is a powerful, high performance object/relational persistence and
query service. This lets the users to develop persistent classes following
object-oriented principles such as association, inheritance, polymorphism,
composition, and collections.
ORM:
ORM stands for Object/Relational mapping. It is the programmed and
translucent perseverance of objects in a Java application in to the tables of a
relational database using the metadata that describes the mapping between
the objects and the database. It works by transforming the data from one
representation to another.
What does an ORM solution comprises of?

It should have an API for performing basic CRUD (Create, Read, Update,
Delete) operations on objects of persistent classes
Should have a language or an API for specifying queries that refer to the
classes and the properties of classes

An ability for specifying mapping metadata

It should have a technique for ORM implementation to interact with


transactional objects to perform dirty checking, lazy association fetching,
and other optimization functions

Different levels of ORM quality:


There are four levels defined for ORM quality.
i.
ii.

Pure relational
Light object mapping

iii.

Medium object mapping

iv.

Full object mapping

What is a pure relational ORM?

The entire application, including the user interface, is designed around the
relational model and SQL-based relational operations.
What is a meant by light object mapping?
The entities are represented as classes that are mapped manually to the
relational tables. The code is hidden from the business logic using specific
design patterns. This approach is successful for applications with a less
number of entities, or applications with common, metadata-driven data
models. This approach is most known to all.
What is a meant by medium object mapping?
The application is designed around an object model. The SQL code is
generated at build time. And the associations between objects are supported
by the persistence mechanism, and queries are specified using an objectoriented expression language. This is best suited for medium-sized
applications with some complex transactions. Used when the mapping
exceeds 25 different database products at a time.
What is meant by full object mapping?
Full object mapping supports sophisticated object modeling: composition,
inheritance, polymorphism and persistence. The persistence layer
implements transparent persistence; persistent classes do not inherit any
special base class or have to implement a special interface. Efficient fetching
strategies and caching strategies are implemented transparently to the
application.
Benefits of ORM and Hibernate:
There are many benefits from these. Out of which the following are the most
important one.
i.
ii.

iii.

Productivity Hibernate reduces the burden of developer by


providing much of the functionality and let the developer to
concentrate on business logic.
Maintainability As hibernate provides most of the functionality,
the LOC for the application will be reduced and it is easy to
maintain. By automated object/relational persistence it even
reduces the LOC.
Performance Hand-coded persistence provided greater
performance than automated one. But this is not true all the times.
But in hibernate, it provides more optimization that works all the

time there by increasing the performance. If it is automated


persistence then it still increases the performance.
iv.

Vendor independence Irrespective of the different types of


databases that are there, hibernate provides a much easier way to
develop a cross platform application.

How does hibernate code looks like:


Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");
session.save(mpc);
tx.commit();
session.close();

The Session and Transaction are the interfaces provided by hibernate. There
are many other interfaces besides this.
What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information
is provided in an xml document. This document is called as xml mapping
document. The document defines, among other things, how properties of the
user defined persistence classes map to the columns of the relative tables in
database.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="sample.MyPersistanceClass" table="MyPersitaceTable">
<id name="id" column="MyPerId">
<generator class="increment"/>
</id>
<property name="text" column="Persistance_message"/>
<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>
</class>
</hibernate-mapping>

Everything should be included under <hibernate-mapping> tag. This is the


main tag for an xml mapping document.

Hibernate overview:

`
Core interfaces of hibernate framework:
There are many benefits from these. Out of which the following are the most
important one.
i.

ii.

Session Interface This is the primary interface used by hibernate


applications. The instances of this interface are lightweight and are
inexpensive to create and destroy. Hibernate sessions are not
thread safe.
SessionFactory Interface This is a factory that delivers the
session objects to hibernate application. Generally there will be a
single SessionFactory for the whole application and it will be shared
among all the application threads.

iii.

Configuration Interface This interface is used to configure and


bootstrap hibernate. The instance of this interface is used by the
application in order to specify the location of hibernate specific
mapping documents.

iv.

Transaction Interface This is an optional interface but the above


three interfaces are mandatory in each and every application. This
interface abstracts the code from any kind of transaction
implementations such as JDBC transaction, JTA transaction.

v.

Query and Criteria Interface This interface allows the user to


perform queries and also control the flow of the query execution.

Callback interfaces:
These interfaces are used in the application to receive a notification when
some object events occur. Like when an object is loaded, saved or deleted.
There is no need to implement callbacks in hibernate applications, but theyre
useful for implementing certain kinds of generic functionality.
Extension interfaces:
When the built-in functionalities provided by hibernate is not sufficient
enough, it provides a way so that user can include other interfaces and
implement those interfaces for user desire functionality. These interfaces are
called as Extension interfaces.
Extension interfaces in hibernate:
There are many extension interfaces provided by hibernate.

ProxyFactory interface - used to create proxies


ConnectionProvider interface used for JDBC connection
management

TransactionFactory interface Used for transaction management

Transaction interface Used for transaction management

TransactionManagementLookup interface Used in transaction


management.

Cahce interface provides caching techniques and strategies

CacheProvider interface same as Cache interface

ClassPersister interface provides ORM strategies

IdentifierGenerator interface used for primary key generation

Dialect abstract class provides SQL support

Different environments to configure hibernate:

There are mainly two types of environments in which the configuration of


hibernate application differs.
Managed environment In this kind of environment everything from
database connections, transaction boundaries, security levels and all are
defined. An example of this kind of environment is environment provided
by application servers such as JBoss, Weblogic and WebSphere.
Non-managed environment This kind of environment provides a basic
configuration template. Tomcat is one of the best examples that provide
this kind of environment.

i.

ii.

What is the file extension you use for hibernate mapping file?
The name of the file should be like this : filename.hbm.xml
The filename varies here. The extension of these files should be .hbm.xml.
This is just a convention and its not mandatory. But this is the best practice to
follow this extension.
Creating a SessionFactory:
Configuration cfg = new Configuration();
cfg.addResource("myinstance/MyConfig.hbm.xml");
cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();

First, we need to create an instance of Configuration and use that instance to


refer to the location of the configuration file. After configuring this instance is
used to create the SessionFactory by calling the method
buildSessionFactory().
Method chaining:
Method chaining is a programming technique that is supported by many
hibernate interfaces. This is less readable when compared to actual java
code. And it is not mandatory to use this format. Look how a SessionFactory
is created when we use method chaining.
SessionFactory sessions = new Configuration()
.addResource("myinstance/MyConfig.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();

What does hibernate.properties file consist of:

This is a property file that should be placed in application class path. So when
the Configuration object is created, hibernate is first initialized. At this moment
the application will automatically detect and read this hibernate.properties file.
hibernate.connection.datasource =java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class =
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class =
net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

Where should SessionFactory be placed so that it can be easily


accessed:
As far as it is compared to J2EE environment, if the SessionFactory is placed
in JNDI then it can be easily accessed and shared between different threads
and various components that are hibernate aware. You can set the
SessionFactory to a JNDI by configuring a property
hibernate.session_factory_name in the hibernate.properties file.

POJOs:
POJO stands for plain old java objects. These are just basic JavaBeans that
have defined setter and getter methods for all the properties that are there in
that bean. Besides they can also have some business logic related to that
property. Hibernate applications works efficiently with POJOs rather then
simple java classes.
What is object/relational mapping metadata:
ORM tools require a metadata format for the application to specify the
mapping between classes and tables, properties and columns, associations
and foreign keys, Java types and SQL types. This information is called the
object/relational mapping metadata. It defines the transformation between the
different data type systems and relationship representations.
HQL:
HQL stands for Hibernate Query Language. Hibernate allows the user to
express queries in its own portable SQL extension and this is called as HQL.
It also allows the user to express in native SQL.
Different types of property and class mappings:

Typical and most common property mapping


<property name="description" column="DESCRIPTION" type="string"/>
Or
<property name="description" type="string">
<column name="DESCRIPTION"/>
</property>

Derived properties

<property name="averageBidAmount" formula="( select AVG(b.AMOUNT)


from BID b where b.ITEM_ID = ITEM_ID )" type="big_decimal"/>

Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>

Controlling inserts and updates


<property name="name" column="NAME" type="string"
insert="false" update="false"/>

Attribute Oriented Programming:


XDoclet has brought the concept of attribute-oriented programming to Java.
Until JDK 1.5, the java language had no support for annotations; now XDoclet
uses the Javadoc tag format (@attribute) to specify class-, field-, or methodlevel metadata attributes. These attributes are used to generate hibernate
mapping file automatically when the application is built. This kind of
programming that works on attributes is called as Attribute Oriented
Programming.
Different methods of identifying an object:
There are three methods by which an object can be identified.
i.

Object identity Objects are identical if they reside in the same


memory location in the JVM. This can be checked by using the = =
operator.

ii.

Object equality Objects are equal if they have the same value,
as defined by the equals( ) method. Classes that dont explicitly
override this method inherit the implementation defined by
java.lang.Object, which compares object identity.

iii.

Database identity Objects stored in a relational database are


identical if they represent the same row or, equivalently, share the
same table and primary key value.

Different approaches to represent an inheritance hierarchy:


i.
ii.

Table per concrete class.


Table per class hierarchy.

iii.

Table per subclass.

Managed associations and hibernate associations:


Associations that are related to container management persistence are called
managed associations. These are bi-directional associations. Coming to
hibernate associations, these are unidirectional.

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