Friday, December 25, 2009

Spring

What is Spring?
Spring is a lightweight inversion of control and aspect-oriented container framework.

Explain Spring?
• Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of springframework 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.
What are the different modules in Spring framework?
• 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
What is the 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.
What is 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.

What is 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 Spring’s metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects.

What is 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 Spring’s AOP module to provide transaction management services for objects in a Spring application.

What are 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. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

What is 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.


Bean lifecycle in Spring framework?
1. The spring container finds the bean’s 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 bean’s 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, theirpostProcessAfterInitialization() methods will be called.
What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

What are the different types of IOC (dependency injection) ?
• Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
• Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
• Interface Injection (e.g. Avalon): Injection is done through an interface.
What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
• A means for resolving text messages, including support for internationalization.
• A generic way to load file resources.
• Events to beans that are registered as listeners.
The three commonly used implementation of 'Application Context' are
• ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code .
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

• FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");

• XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
What are singleton beans and how can you create 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.



What are the important 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.
How can you 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.
What do you mean by Bean wiring ?
The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring. Or
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.
What do you mean by Auto Wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. Or
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.
The autowiring functionality has five modes.
• no
• byName
• byType
• constructor
• autodetect

Different types of events related to Listeners?
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses oforg.springframework.context.Application-Event. 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.
What is an 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.

What is a 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 aspect’s code can be inserted into the normal flow of your application to add new behavior.

What is an 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.

What is a 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.

What is an 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.
What is a 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.
What is a 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.
What is meant by 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.
What are the different points where weaving can be applied?
Compile Time
Classload Time
Runtime
What are the different advice types in spring?
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
What are the different types of AutoProxying?
BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator
Metadata autoproxying
What is the Exception class related to all the exceptions that are thrown in spring applications?
DataAccessException - org.springframework.dao.DataAccessException
How can you configure a bean to get DataSource from JNDI?



java:comp/env/jdbc/myDatasource


44) How can you create a DataSource connection pool?



${db.driver}


${db.url}


${db.username}


${db.password}



What are the ways to access Hibernate using Spring ?
• Inversion of Control with a HibernateTemplate and Callback
• Extending HibernateDaoSupport and Applying an AOP Interceptor
What are Bean scopes in Spring Framework ?
The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). The scopes supported are listed below:
Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware SpringApplicationContext.

What are the types of Advice?
Types of advice:
• Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
• After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
• After throwing advice: Advice to be executed if a method exits by throwing an exception.
• After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
• Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception
What is SQLExceptionTranslator ?
SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic org.springframework.dao.DataAccessException.

Transaction Isolation Levels

1. ISOLATION_DEFAULT
2. ISOLATION_READ_UNCOMMITTED
- Dirty reads, non-repeatable reads and phantom reads can occur.
3. ISOLATION_READ_COMMITTED
– Dirty reads are prevented; non-repeatable reads and phantom reads can occur.
4. ISOLATION_REPEATABLE_READ
– Dirty reads and non-repeatable reads are prevented; phantom reads can occur.
5. ISOLATION_SERIALIZABLE
– Dirty reads, non-repeatable reads and phantom reads are prevented


Transaction Propagation
1.PROPAGATION_REQUIRED
– Support a current transaction, create a new one if none exists.
2.PROPAGATION_SUPPORTS
– Support a current transaction, execute non-transactionally if none exists.
3. PROPAGATION_MANDATORY
– Support a current transaction, throw an exception if none exists.
4. PROPAGATION_REQUIRES_NEW
– Create a new transaction, suspend the current transaction if one exists.
5.PROPAGATION_NOT_SUPPORTED
–Always Executes non-transactionally, suspend the current transaction if active transaction exists.
6. PROPAGATION_NEVER
–Always Executes non-transactionally, Exception thrown if active transaction exists.
7. PROPAGATION_NESTED
– Runs Nested transaction if one exists. Otherwise Executes PROPAGATION_REQUIRED.


Anomaly Example
Dirty Reads
A dirty read happens when a transaction reads data that is being modified by another transaction that has not yet committed. Transaction A begins.
UPDATE employee SET salary = 31650
WHERE empno = '000090'
Transaction B begins.
SELECT * FROM employee
(Transaction B sees data updated by transaction A. Those updates have not yet been committed.)
Non-Repeatable Reads
Non-repeatable reads happen when a query returns data that would be different if the query were repeated within the same transaction. Non-repeatable reads can occur when other transactions are modifying data that a transaction is reading. Transaction A begins.
SELECT * FROM employee
WHERE empno = '000090'
Transaction B begins.
UPDATE employee SET salary = 30100
WHERE empno = '000090'
(Transaction B updates rows viewed by transaction A before transaction A commits.) If Transaction A issues the same SELECT statement, the results will be different.
Phantom Reads
Records that appear in a set being read by another transaction. Phantom reads can occur when other transactions insert rows that would satisfy the WHERE clause of another transaction's statement. Transaction A begins.
SELECT * FROM employee
WHERE salary > 30000
Transaction B begins.
INSERT INTO employee
(empno, firstnme, midinit,
lastname, job,
salary) VALUES ('000350', 'NICK',
'A','GREEN','LEGAL COUNSEL',35000)
Transaction B inserts a row that would satisfy the query in Transaction A if it were issued again.

No comments:

Post a Comment