You are on page 1of 85

Spring interview questions - posted on June 27, 2013 at 17:05 PM by Kshipra Singh

1. Differentiate between BeanFactory and ApplicationContext in spring.


- With ApplicationContext more than one config files are possible while only one config file or .xml file is possible with BeanFactory. - ApplicationContext publishes events to beans that are registered as listeners while BeanFactory doesn't support this - ApplicationContext support internationalization messages, application life-cycle events, validation and many enterprise services like JNDI access, EJB integration, remoting etc. while BeanFactory doesn't support any of these.

2. What is the difference between singleton and prototype bean?


Mainly it is the scope of a beans which defines their existence on the application - Singleton: It means single bean definition to a single object instance per Spring IOC container. - Prototype: It means a single bean definition to any number of object instances.

3. How do beans become 'singleton' or prototype?


- There exists an attribute in bean tag, called 'singleton. - If it is marked 'true', the bean becomes singleton. - If it is marked 'false', the bean becomes prototype.

4. What type of transaction Management Spring support?


Spring supports two types of transaction management: 1. Programmatic transaction management 2. Declarative transaction management.

5. When do you use programmatic and declarative transaction management ?


- Programmatic transaction management is used preferably when you have a small number of transactional operations. - Incase of large number of transactional operations it is better to use declarative transaction management.

6. What is IOC?

- IOC stands for Inversion of Control pattern. - It is also called as dependency injection. - This concept says that you do not create your objects but describe how they should be created. - Similarly, you do not directly connect your components and services together in code but describe which services are needed by which components in a configuration file. - A container then hooks them all up.

7. What are the different types of IoC (dependency injection) ?


There are three types of dependency injection: a.) Constructor Injection : Here dependencies are provided as constructor parameters. b.) Setter Injection : Dependencies are assigned through JavaBeans properties. c.) Interface Injection : Injection is performed through an interface. Spring supports only first two categories of Injection.

8. What are the benefits of IOC?


The main benefits of IOC or dependency injection are: a.) It minimizes the amount of code in your application. b.) It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases. c.) Loose coupling is promoted with minimal effort and least intrusive mechanism. d.) IOC containers support eager instantiation and lazy loading of services.

9. What is Bean Wiring ?


Bean wiring means creating associations between application components i.e. beans within the spring container.

10. How do you access Hibernate using Spring ?


There are two ways to Springs Hibernate integration: a.) By Inversion of Control with a HibernateTemplate and Callback b.) By extending HibernateDaoSupport and Applying an AOP Interceptor

11. How would you integrate Spring and Hibernate using HibernateDaoSupport?

This can be done through Springs SessionFactory called LocalSessionFactory. The steps in integration process are: a.) Configure the Hibernate SessionFactory b.) Extend your DAO Implementation from HibernateDaoSupport c.) Wire in Transaction Support with AOP

12.What are the various transaction manager implementations in Spring ?


1. DataSourceTransactionManager : PlatformTransactionManager implementation for single JDBC data sources. 2. HibernateTransactionManager: PlatformTransactionManager implementation for single Hibernate session factories. 3. JdoTransactionManager : PlatformTransactionManager implementation for single JDO persistence manager factories. 4. JtaTransactionManager : PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions.

What is Spring?

The Spring Framework is an open source application framework for the Java platform and .NET Framework (Spring.NET), its core features can be used by any Java application, its basically is a lightweight inversion of control and aspect-oriented container framework. Though Spring Framework does not promote any specific programming model, but it promotes 'POJO' approach which enables us to take advantage of environment-specific features without sacrificing portability. Features which make Spring Framework different from other such frameworks are:

It addresses important areas that many other popular frameworks don't, by focusing around providing a way to manage your business objects. Spring is both comprehensive and modular. Spring has a layered architecture, meaning that you can choose to use just about any part of it in isolation. Spring is an ideal framework for test driven projects.

Explain the different modules in Spring framework.

Spring has the following modules:

The Core container module The fundamental functionality is provided by this module Application context module - Spring is a framework because of this module. This module extends the concept of BeanFactory. AOP module (Aspect Oriented Programming) This is module is for using aspects of spring based applications. JDBC abstraction and DAO module To make database code cleanup and to prevent problems at the time of closing database resources, this module is used. O/R mapping integration module (Object/Relational) This module is used to tie up with ORM tools such as hibernate. Web module The context for an appropriate web-based application, this module is used.

Different modules offered by Spring Framework are:


Inversion of Control container: configuration of application components and lifecycle management of Java objects Aspect-oriented programming: enables implementation of cross-cutting routines Data access: working with relational database management systems on the Java platform using JDBC and object-relational mapping tools Transaction management: unifies several transaction management APIs and coordinates transactions for Java objects Model-view-controller: an HTTP and Servlet-based framework providing hooks for extension and customization Remote Access framework: configurative RPC-style export and import of Java objects over networks supporting RMI, CORBA and HTTP-based protocols including web services (SOAP) Batch processing: a framework for high-volume processing featuring reusable functions including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management Authentication and authorization: configurable security processes that support a range of standards, protocols, tools and practices via the Spring Security sub-project (formerly Acegi). Remote Management: configurative exposure and management of Java objects for local or remote configuration via JMX Messaging: configurative registration of message listener objects for transparent message consumption from message queues via JMS, improvement of message sending over standard JMS APIs Testing: support classes for writing unit tests and integration tests

What are the Core container module and Application context module?

Core Container Module: This module is the fundamental module of spring framework. For a spring-based application, BeanFactory is the core. The Spring framework was developed on top of this module. Spring container is made by this module. Application Context Module: Spring is called a framework because of this module. The concept of BeanFactory is used to extend this module to provide support for internationalization

(I18N) messages etc. Enterprise services such as JNDI,EJB integration, remoting and scheduling are supplied by this module. This module 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. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code. 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 a BeanFactory and XMLBeanFactory?

BeanFactory: Bean factory is a container. It configures, instantiates and manages a set of beans. These beans are collaborated with one another and have dependencies among themselves. The reflection of these dependencies are used in configuring data that is used by BeanFactory. XMLBeanFactory: XMLBeanFactory is a bean factory that is loaded its beans from an XML file. he BeanFactory provides an advanced configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage facility. The BeanFactory is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the BeanFactory.A BeanFactory is represented by the interface org.springframework.beans.factory.BeanFactory, for which there are multiple implementations. Although for most scenarios, almost all user code managed by the BeanFactory does not have to be aware of the BeanFactory, the BeanFactory does have to be instantiated somehow. This can happen via explicit user code such as: Resource res = new FileSystemResource("beans.xml"); XmlBeanFactory factory = new XmlBeanFactory(res); or ClassPathResource res = new ClassPathResource("beans.xml"); XmlBeanFactory factory = new XmlBeanFactory(res); or

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml", "applicationContext-part2.xml"}); // of course, an ApplicationContext is just a BeanFactory BeanFactory factory = (BeanFactory) appContext; 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");
What is AOP Alliance?

AOP Alliance: AOP Alliance is an open source project. Promoting adoption of AOP and interoperability among different AOP implementations with the help of interfaces and components that are well defined, are the main goals of AOP Alliance. Aspect-Oriented Programming (AOP) is a great way for designing and programming the applications. It offers a better solution to many problems than do existing technologies such as EJB. In Spring, Aspect-Oriented Programming (AOP) it a consistent AOP infrastructure that can be applied for other AOP technical solutions. Out of the gate, spring supports dynamic-proxybased AOP, and CGLib-based AOP Spring's 'built-in' AOP infrastructure is defined by the org.springframework.aop.* AOP provides a generic means to build new technical concerns (crosscutting concerns) and to plug them within an application in a flexible and modular way. Applying some AOP concepts in J2EE can also really simplify its use.
Explain the concepts and purpose of Spring configuration file.

A spring configuration file is an XML file which contains the information about classes and describes the process of configuration.
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.

What does a simple spring application contain?

A spring application is like any other Java application. The applications contain classes, each of them perform a specific task with the application. All these classes are configured and introduced to other classes with the help of an XML file. The configuration process is described in the Spring configuration file.
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. Explain Bean lifecycle in Spring framework.

The beans definition is found by the spring container from the XML file and instantiates the bean. All the properties specified in the bean definition are populated by spring using dependency injection. The beans Id is passed to setBeanName() method by the factory, and the factory calls setBeanFactory() is passed to itself, incase the bean implements the BeanFactoryAware interface. The init() method is invoked if specified. If any BeanPostProcessors are associated with the bean, the methods postProcessAfterInitialization() are invoked.
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. What is bean wiring?

Bean wiring is the process of combining beans with Spring container. The required beans are to be informed to the container and how the container should use dependency injection to tie them together, at the time of wiring the beans.
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.

Explain how to add a bean in spring application.

The id attribute of the bean tag specifies the name of the bean and the fully qualified class name is specified by the class attribute. The following is the fragment of the XML file of spring which illustrates the bean and class attributes. <bean> <bean id=bar class=com.act.SomeAction singleton=false/> </bean> <?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.
Spring - What are singleton beans and how can you create prototype beans? - Feb 24, 2009, 19:00 pm by Vidya Sagar What are singleton beans and how can you create prototype beans?

All beans defined in the spring framework are singleton beans. The bean tag has an attribute by name singleton. To make the bean singleton, assign true for this attribute. The default value is true, and hence all the beans in spring are by default singleton 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>
What are Inner Beans?

A bean inside another bean is known as Inner Bean. They are created and used on the fly, and can not be used outside the enclosing beans. The Id and scope attributes for inner beans are of no use.

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. What is Auto wiring? What are different types of Autowire types?

Searching for objects with the same name of object property is called auto wiring in Spring. By default, Spring framework enables the auto wiring. There are 4 different types of auto wiring. They are byName byType constructor autodetect It is possible to automatic resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. 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> There are four different types by which auto wiring can be done.

byName byType constructor autodetect

What is meant by Weaving? What are the different points where weaving can be applied?

The process of applying aspects to a target object for creating a new proxy object is referred to as weaving. These aspects are woven at the following specified join points: Compile Time Classload Time Runtime In Spring AOP makes it possible to modularize and separate logging, transaction like services and apply them declaratively to the components Hence programmer can focus on specific concerns. Aspects are wired into objects in the spring XML file in the way as JavaBean. This process is known as '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.

Compile Time Classload Time Runtime

Explain the different types of AutoProxying.

BeanNameAutoProxyCreator: This proxy is used to identify beans to proxy through a list of names. It checks the matches that are direct, xxx and *xxx. DefaultAdvisorAutoProxyCreator: This proxy is the implementation of BeanPostProcessor which creates AOP proxies. These AOP proxies are based on BeanFactorys all Candidate Advisors. It is a generic class which does not have a specific code to handle any specific aspects. Metadata autoproxying: The metadata autoproxy is concerned with the possibility to employ annotations in certain classes, like defining transactions. To configure this type of proxies, the source level metadata interpretation and the bean usage that employs those attributes is done by DefaultAdvisorAutoProxyCreator.
What is DataAccessException?

DataAccessException is an unchecked RuntimeException. These type of exceptions are unforced by users to handle. This exception is used to handle the errors occurring when the details of the database access API in use, such as JDBC.
DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions. What is PreparedStatementCreator?

To write data to database, PreparedStatementCreator is the most commonly used interface. The interface contains one method by name createPreparedStatement(). Returning a PreparedStatement is need when this interface is implemented. Another interface, SqlProvider is also implemented along with this interface, which has a method getSql() for providing sql strings to JdbcTemplate. 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.
What is BatchPreparedStatementSetter?

Updating more than one row at a time, the BatchPreparedStatementSetter is used. This interface has setValues() and getBatchSize() exceptions. The getBatchSize() method is used to specify the number of statements to create. 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.
What is RowCallbackHandler? Why it is used.

ResultSet is generally used to navigate the records. The spring framework is provided with RowCallbackHandler interface. The method processRow() can be implemented for use of navigation and handling each row. The user can concentrate only on what to do with each row by avoiding navigation process. The processRow() method has the following signature: void processRow(java.sql.ResultSet rs); 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);
20. Give examples of how spring platform can be used by an application developer.

The spring platform can be used by an application developer in the following way :: Java method can be made to execute in a database transaction without having to deal with transaction APIs. Local Java method can be made a remote procedure without having to deal with remote APIs. Local Java method can be made a management operation without having to deal with JMX APIs. Local Java method can be made a message handler without having to deal with JMS APIs.

21. What are the various ways of using spring?

There are various ways and forms in which springs can be used. They are listed as follows: 1. Full-fledged Spring web app 2. Spring middle-tier provides help of a third-party web framework 3. Remote usage scenario: allow the system to be used to remotely use the resources from the server. The remote usage can be done to grab the data from the server or for troubleshooting the environment. 4. EJB -- Wrapping existing POJOs
22. Specify the locations where spring can publish its artifacts.

Spring generally publishes its artifacts to four different places: 1. Community download site http://www.springsource.org/downloads/community. 2. Maven Central, which is considered the default repository that Maven queries, and does not require any special configuration to use. 3. The Enterprise Bundle Repository (EBR), which is considered to be run by SpringSource and also hosts all the libraries that integrate with Spring. 4. Public Maven repository hosted on Amazon S3 for the development of snapshots and milestone releases. The jar file names are given in the same form as Maven Central, which makes it a useful place to get development versions of Spring to use with other libraries Spring Framework deployed in Maven Central.
23. What are the features of the new spring build system in use now days?

Now the new Spring build system is used which comes with the following features : 1. "Spring Built" system which is based on Ivy 2. consistent procedure for deployment 3. dependency management which is made consistent 4. consistent generation for OSGi
24. List in brief the new features Spring 3.0 has to offer

Spring 3.0 offers the following new features: 1. Spring Expression Language 2. IoC enhancements or Java based bean metadata 3. field formatting and General-purpose type conversion system 4. Object to XML mapping functionality (OXM) moved from Spring Web Services project 5. Comprehensive REST support 6. @MVC additions 7. Declarative model validation 8. Early support for Java EE 6 9. Embedded database support

25. What are the annotations supported by the spring framework?

Due to addition of some core features from the JavaConfig project to the Spring Framework,the following annotations are now directly supported: @Configuration @Bean @DependsOn @Primary @Lazy @Import @ImportResource @Value
26. Explain in brief the metadata contained in the BeanDefinition objects

Bean definitions contain the following metadata: 1. A package-qualified class name: which is the actual implementation class of the bean being defined. 2. Bean behavioral configuration elements, which state the procedure for how the bean should behave in the container 3. References to other beans that are required for the bean to do its work; these references are also called collaborators or dependencies. 4. Other configuration settings to set when a new object is created, for example, the number of connections to use in a bean that manages a connection pool or the size limit of the pool.
27. What are the different properties the metadata translates into to make up the bean definition?

Metadata translates into the following properties to make up 1. Property defined in class the section called Instantiating beans 2. Property defined in name the section called Naming beans scope constructor arguments the section known as Dependency injection 3. Properties the section known as Dependency injection auto wiring mode the section known as Autowiring collaborators 4. lazy-initialization mode the section called Lazy-initialized beans 5. Initialization method the section called Initialization callbacks 6. Destruction method the section called Destruction callbacks
28. Briefly describe the 2 ways in which the class property can be used.

The class property can be put to use in the following ways: 1. It is used to specify the java bean for class to be constructed when container directly creates java bean by calling constructor reflectively. This procedure is also used for java code which uses a new operator. 2. It is also used to specify the class which contains static factory method which is invoked for

creating object. Another case in this which doesnt occur much is when static factory method is invoked by container on a class for creating the bean.
29. Explain the dependency resolution process.

The dependency resolution process is carried out as follows: 1. Creation an initialization of application text inside configuration metadata( can be specified in XML, java code,annotations) is done. This describes all the beans. 2. For each bean, its dependency is expressed in the form of properties, constructor arguments, or arguments to the static-factory method if that is used instead of a normal constructor. 3. Each property or constructor argument is actual definition of the value which belong to set, or a reference to another bean which is in the container. 4. Each property or constructor argument which is a value is gone through conversion from its specified format to the actual type of that property or constructor argument.
30. How can you use spring to resolve collaborators for your bean? Also state the advantages of auto wiring?

The spring can be used to resolve collaborators automatically by inspecting contents of the ApplicationContext. The Autowiring has the following advantages in spring: 1. Reduces requirement for specifying properties or construction arguments. 2. Updates configuration while evolving of objects. To understand this lets consider an example: modifying would not be required in configuration of a dependency while adding it to a class. 3. Switching to explicit wiring when code base is stable can be neglected.
31. List the limitations of auto wiring.

Autowiring has the following limitations: 1. Overriding and auto wiring are caused due to dependency in property and constructor argument setting. 2. Less precise as compared to explicit wiring. 3. Tools that generate documentation using a spring might not have access to wiring information. 4. There is a possibility of clash between bean definitions and argument or method to be wired. The problem does not occur much in case of maps, arrays and collection and cannot be resolved randomly for dependencies which expect one value.
32. In scenarios where you have to avoid using auto wiring, what are the other options that can be explored to achieve the same.

In scenarios where using autowiring is prohibited, the following replacements can achive the same: 1. Abandon autowiring for favor of explicit wiring. 2. Avoid autowiring for a bean definition by setting the autowire-candidate for attributes to false as described in the next section.

3. Set a single bean definition as the primary candidate by setting the primary attribute of its <bean/> element to true. 4. When Java 5 or later is used, implementation needs more fine-grained control available with annotation-based configuration.
33. How do you call the multiple lifecycle mechanisms configured for the same bean?

Multiple lifecycle mechanisms which are configured for the same bean, with different initialization methods, are called by the following ways : 1. Methods annotated with use of @PostConstruct 2. afterPropertiesSet() as stated by the InitializingBean callback interface 3. Custom configuration init() method Destroy methods are called in the same order as follows : 1. Methods annotated with use of @PreDestroy 2. destroy() as stated by the DisposableBean callback interface 3. destroy() method with custom configuration
34. What are the methods associated with the FactoryBean interface?

Following are the methods associated with factory bean interface: 1> Object getObject(): this returns an instance of the object which the factory creates. This instance can possibly be shared, depending on the factory returns singletons or prototypes. 2> boolean isSingleton(): this returns true if this FactoryBean returns singletons, false otherwise. 3> Class getObjectType(): this returns the object type returned by the getObject() method or null if the type is unknown in advance.
35. What are the functionalities provided by the context package to enhance the BeanFactory functionality?

The functionalities provided by context package are as follows: 1. message access in i18n-style, through the MessageSource interface. 2. Resources access such as URLs and files, through which, the ResourceLoader interface, can be accessed and used. 3. Publication of events, through the beans that allow, implementing the ApplicationListener interface. It is done through the use, of the ApplicationEventPublisher interface. 4. Multiple loading contexts, allowing each to be focused on one particular layer, such as the web layer of an application, through the HierarchicalBeanFactory interface.
36. How can you achieve Internationalization using MessageSource?

Internationnalization using message source can be achieved by the following: 1>String get Mesage(String code, Objct[] args, String default, Local loc): The basic method used for retrieving a message from the MessageSource. When no message is to be

found for the specified locale, the default message is used. 2> String getMessage(String code, Objct[] args, Locale loc): Essentially the same as the last method, but with a difference: no default message is specified; if the message cannot be found, a NoSuchMessageException is shown. 3> String getMessage(MessageSourceResolvable resolvable, Local locale): properties used for the preceding methods are also wrapped in a class named MessageSourceResolvable, which you can use with this method.
37. Enlist and explain the main methods associated with the Resource interface.

Methods associated with resource interface are as follows: 1> getInputStream(): it locates and opens the resource, returning an InputStream to read from the resource. 2> exists(): returns a boolean which indicates whether this resource actually exists in physical form. 3> isOpen(): returns a boolean which indicates whether this resource represents a handle with an open stream. 4> getDescription(): returns a description for this resource, which is used for error output when working with the resource.
38. Give some examples where property editing is used in spring.

Following are examples for property editing in spring 1> setting of properties on beans is done by using PropertyEditors. To mention java.lang.string as the value for a property of some bean you're declaring in XML file, Spring will use the ClassEditor to try resolving the parameter to a Class object. 2> passing HTTP request parameters in Spring's MVC framework can be done using all kinds of PropertyEditors that can be manually bind in all subclasses of the CommandController.
40. Explain the main AOP concepts and terminology

The main AOP concepts are as follows: 1> Aspect: a modularization of a concern that cuts through multiple classes. 2> Join point: is a point during which the execution of a programming, such as the execution of method or handling of an exception. 3> Advice: action taken by an aspect for a particular join point. 4> Point cut: a predicate that is matched to join points. 5> Introduction: declaration of additional methods or fields on behalf of a type. 6> Target object: object which is advised by one or more aspects. 7> AOP proxy: an object which is created by AOP framework for implementing the aspect contracts. 8> Weaving: linking of aspects with other application types or objects to create an advised object.

1) What is Spring?
Answer:

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

2) Explain Spring?
Answer:

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.

3) What are the different modules in Spring framework?


Answer:

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

4) What is the structure of Spring framework?

Answer:

5) What is the Core container module?


Answer:

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.

6) What is Application context module?


Answer:

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.

7) What is AOP module?


Answer:

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 addannotations to our source code that instruct Spring on where and how to apply aspects.

8) What is JDBC abstraction and DAO module?


Answer:

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.

9) What are object/relational mapping integration module?


Answer:

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.

10) What is web module?


Answer:

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.

11) What is Spring MVC?


Answer:

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.

12) What is a BeanFactory?

Answer:

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.

13) What is AOP Alliance?


Answer:

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.

14) What is Spring configuration file?


Answer:

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.

15) What does a simple spring application contain?


Answer:

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.

16) What is XMLBeanFactory?


Answer:

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. TheInputStream 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);

17) What are important ApplicationContext implementations in spring framework?


Answer:

ClassPathXmlApplicationContext This context loads a context definition from an XML file located in theclass 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.

18) Explain Bean lifecycle in Spring framework?


Answer: 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 aninstance of itself. 5. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization()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.

19) What is bean wiring?


Answer:

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.

20) How do add a bean in spring application?


Answer:
1 <?xml version="1.0" encoding="UTF-8"?>

2 3 4 5 6

<!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 classname.

21) What are singleton beans and how can you create prototype beans?
Answer:

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.
1 <beans> 2 3 <bean id="bar" class="com.act.Foo" singleton=false/> </beans>

22) What are the important beans lifecycle methods?


Answer:

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.

23) How can you override beans default lifecycle methods?

Answer:

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.
1 <beans> 2 3 <bean id="bar" class="com.act.Foo" init-method=fooSetup destroy=fooTeardown/> </beans>

24) What are Inner Beans?


Answer:

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.

25) What are the different types of bean injections?


Answer:

There are two types of bean injections.


1. By setter 2. By constructor

26) What is Auto wiring?


Answer:

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.
1 <beans> 2 3 <bean id="bar" class="com.act.Foo" Autowire=autowire type/> </beans>

27) What are different types of Autowire types?


Answer:

There are four different types by which autowiring can be done.


o o o o

byName byType constructor autodetect

28) What are the different types of events related to Listeners?


Answer:

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.

29) What is an Aspect?


Answer:

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 yourapplication using AOP.

30) What is a Jointpoint?


Answer:

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.

31) What is an Advice?


Answer:

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.

32) What is a Pointcut?


Answer:

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.

33) What is an Introduction in AOP?


Answer:

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.

34) What is a Target?


Answer:

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.

35) What is a Proxy?


Answer:

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.

36) What is meant by Weaving?

Answer:

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.

37) What are the different points where weaving can be applied?
Answer:

Compile Time Classload Time Runtime

38) What are the different advice types in spring?


Answer:

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

39) What are the different types of AutoProxying?


Answer:

BeanNameAutoProxyCreator DefaultAdvisorAutoProxyCreator Metadata autoproxying

40) What is the Exception class related to all the exceptions that are thrown in spring applications?
Answer:

DataAccessException org.springframework.dao.DataAccessException

41) What kind of exceptions those spring DAO classes throw?


Answer:

The springs DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are subclasses of DataAccessException.

42) What is DataAccessException?


Answer:

DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions.

43) How can you configure a bean to get DataSource from JNDI?
Answer:
1 <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 2 3 4 5 <property name="jndiName"> <value>java:comp/env/jdbc/myDatasource</value> </property> </bean>

44) How can you create a DataSource connection pool?


Answer:
01 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 02 03 04 05 <property name="driver"> <value>${db.driver}</value> </property> <property name="url">

06 07 08 09 10 11 12 13 14

<value>${db.url}</value> </property> <property name="username"> <value>${db.username}</value> </property> <property name="password"> <value>${db.password}</value> </property> </bean>

45) How JDBC can be used more efficiently in spring framework?


Answer:

JDBC can be used more efficiently with the help of a template class provided by spring framework called asJdbcTemplate.

46) How JdbcTemplate can be used?


Answer:

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.
1 public class StudentDaoJdbc implements StudentDao { 2 3 private JdbcTemplate jdbcTemplate;

4 5 6 7 8

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } more.. }

The configuration is shown below.


01 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 02 03 04 05 06 07 08 09 10 11 12 13 14 15 <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>

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

Answer:

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.

48) Explain about PreparedStatementCreator?


Answer:

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 interfaceSqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.

49) Explain about BatchPreparedStatementSetter?


Answer:

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.

50) Explain about RowCallbackHandler and why it is used?


Answer:

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 isRowCallbackHandler. 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);

What is role of Controller in Spring MVC framework?


In a general way, Controller (c in mvc ) delivers access to the behavior of application which is usually defined by a service interface and acts as glue between core application and the web. It processes/interprets client data and transforms it to a domain object called model, which is finally represented to the client by the view. Spring framework provides wide range of controllers. In a specific way, Spring controllers are based on org.springframework.web.servlet.mvc.Controller Interface. Controller interface provides a single method that handles a request and returns a particular model and view as given in code snippet below. 1public interface Controller { 2 ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response) throws 3 Exception; 4

What is a front controller in Spring MVC ?


A front controller is defined as a controller which handles all requests for a Web Application. DispatcherServlet (actually a servlet) is the front controller in Spring MVC that intercepts every request and then dispatches/forwards requests to an appropriate controller. The DispatcherServlet is declared in the web.xml file of web application. Requests which we want to be handled by DispatcherServlet should be mapped using URL mapping. For example all requests ending with *.htm will be handled by the DispatcherServlet. 1 <web-app> 2 <servlet> 3 <servlet-name>example</servlet-name> 4 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet5 class> <load-on-startup>1</load-on-startup> 6 </servlet> 7 <servlet-mapping> 8 <servlet-name>example</servlet-name> 9 <url-pattern>*.htm</url-pattern> 10</servlet-mapping> </web-app> 11

SimpleFormController example Spring MVC

It offers you form submission support. This can help in modeling forms and populating them with model/command object returned by the controller. After filling the form, it binds the fields, validates the model/command object, and passes the object back to the controller so that the controller can take appropriate action. It supports features like invalid form submission, validating form data, and normal form workflow. SimpleFormController lets you specify a model/command object, a viewname for your form, a viewname for the page you want to display the user when form submission is successful. In this tutorial user is first showed the welcome page (index.html) where on clicking the given link it takes the user to Application form (fillForm.jsp). User fills in the details, submits the form and finally he is shown another page containing the details that he filled previously. Things you will learn in this tutorials : Spring MVC basic flow (data flow from view to controller and rendering model data back to view) Use of SimpleFormController Use of SimpleUrlHandlerMapping Use of InternalResourceViewResolver Use of referenceData(),Spring API Use of formBackingObject(),Spring API Index.html :

fillForm.jsp :

viewForm.jsp

Project Explorer :

How all this works : When you run the application on server it will show you the index.html page because it is specified as welcome file in web.xml. On clicking the given link in index.html it takes you to fillForm.jsp. Link generates a request as

http://localhost:8080/Spring_SimpleFormController/fillFormProcess.dev . All the request with url *.dev are to be processed by DispatcherServlet as we specified this mapping in web.xml. DispatcherServlet receives the request and asks the handler mapping (SimpleUrlHandlerMapping here) to which controller delegate the request. SimpleUrlHandlerMapping (in dispatcher-servlet.xml) tells that a request ending with url fillFormProcess.dev is to be handled by processApplicationFormController bean as given below 1<bean 2class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> 3 <value> 4 fillFormProcess.dev = processApplicationFormController 5 </value> </property> 6 </bean> 7 Finally request is received by processApplicationFormController bean and ProcessApplicationFormController which extends SimpleFormController is invoked. In definition of processApplicationFormController bean (in dispatcher-servlet.xml) we mentioned fillForm as formView so this controller returns view name as fillForm to DispatcherServlet. DispatcherServlet uses ViewResolver mapping to resolve the fillForm to /WEB-INF/jspViews/fillForm.jsp i.e.(prefix+viewname+suffix) and hence fillForm.jsp is shown to user. 1 2 3 4 <bean id="processApplicationFormController" 5 class="com.thecafetechno.ProcessApplicationFormController"> // fillForm is shown when request comes to this controller 6 <property name="formView" value="fillForm" /> 7 // viewForm is shown after successful submit <property name="successView" value="viewForm" /> 8 </bean> 9 1 0 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalR 1 esourceViewResolver"> 1 <property name="prefix"> <value>/WEB-INF/jspViews/</value> 1 </property> 2 <property name="suffix"> 1 <value>.jsp</value> 3 </property> </bean> 1 4 1 5

After filling and submitting fillForm.jsp form, viewForm.jsp is shown because it is specified as successView in definition of processApplicationFormController bean. How all this works : Graphical Representation of Spring MVC using SimpleFormController.

MtnlModel.java : 1 package com.thecafetechno; 2 public class MtnlModel { public String userName; 3 public String address; 4 public String sex; public String plan; 5

6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42} 43 44 45 46 47 48 49

public String [] options; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPlan() { return plan; } public void setPlan(String plan) { this.plan = plan; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String[] getOptions() { return options; } public void setOptions(String[] options) { this.options = options; }

Index.html :

1 2 3 4 5 6 7 8 9 1 0 1 1

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1> Welcome to MTNL Delhi</h1> <a href="http://localhost:8080/Spring_SimpleFormController/fillFormProcess.dev" >Click here to apply for fresh MTNL Broadband Connection</a> </body> </html>

web.xml : 1 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 6 7 <display-name>Spring Web MVC Application</display-name> 8 9 <servlet> <servlet-name>dispatcher</servlet-name> 10 <servlet11 class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 12 <load-on-startup>1</load-on-startup> 13 </servlet> 14 15 <servlet-mapping> <servlet-name>dispatcher</servlet-name> 16 <url-pattern>*.dev</url-pattern> 17 </servlet-mapping> 18 19 <context-param> 20 <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> 21 </context-param> 22 23 24 <listener> <listener-class> 25 org.springframework.web.context.ContextLoaderListener 26 </listener-class> 27 </listener> 28 29 <welcome-file-list> <welcome-file>index.html</welcome-file> 30 </welcome-file-list>
<?xml version="1.0" encoding="UTF-8"?>

31</web-app> 32 33 34 dispatcher-servlet.xml : 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <value> fillFormProcess.dev = processApplicationFormController </value> </property> </bean> <bean id="processApplicationFormController" class="com.thecafetechno.ProcessApplicationFormController"> <property name="formView" value="fillForm" /> <property name="successView" value="viewForm" /> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewReso lver"> <property name="prefix"> <value>/WEB-INF/jspViews/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>

2 5 2 6 2 7 ProcessApplicationFormController : ProcessApplicationFormController extends SimpleFormController So inherits the form submission capabilities. Overridden onSubmit method is invoked when submit button is clicked on fillForm.jsp. It returns a ModelAndView object containing viewForm.jsp (getSuccessView()) as view and modelDataToRender as model. Overridden referenceData() method is used to provide some additional information to the formView (fillForm.jsp) to display the view e.g. availableOptions and availablePlans in this case. Overridden formBackingObject method is used to provide view with model object so that view can be initialized with some default values e.g. model object mtnlModel contains Modem and Landline set as default values for instance variable options of MtnlModel class, this model object is used by Spring to initialize the formView (fillForm.jsp) with default values (Modem and Landline set checkboxes as checked by default). 1 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 8 9 import org.springframework.validation.BindException; 10import org.springframework.web.servlet.ModelAndView; 11import org.springframework.web.servlet.mvc.SimpleFormController; 12 13public class ProcessApplicationFormController extends SimpleFormController { 14 public ProcessApplicationFormController() { 15 setCommandClass(MtnlModel.class); 16 } 17 18 @Override protected ModelAndView onSubmit(HttpServletRequest request, 19 HttpServletResponse response, Object command, BindException 20 errors) 21 throws Exception { 22
package com.thecafetechno;

MtnlModel mtnlModel = (MtnlModel)command; 23 return new 24 ModelAndView(getSuccessView(),"modelDataToRender",mtnlModel); 25 } 26 27 @Override protected Map<String, List<String>> referenceData(HttpServletRequest 28 request) throws Exception { 29 List<String> listOfOptions = new ArrayList<String>(); 30 listOfOptions.add("Modem"); 31 listOfOptions.add("Extra cable"); 32 listOfOptions.add("Landline set"); 33 List<String> listOfPlans = new ArrayList<String>(); 34 listOfPlans.add("Rs:399"); 35 listOfPlans.add("Rs:599"); 36 listOfPlans.add("Rs:799"); 37 listOfPlans.add("Rs:999"); Map<String, List<String>> map = new HashMap<String, List<String>>(); 38 map.put("availablePlans", listOfPlans); 39 map.put("availableOptions", listOfOptions); 40 return map; 41 } 42 43 @Override protected Object formBackingObject(HttpServletRequest request) throws 44 Exception { 45 String[] options = {"Modem","Landline set"}; 46 MtnlModel mtnlModel = new MtnlModel(); 47 mtnlModel.setOptions(options ); 48 return mtnlModel; } 49 50 51} 52 53 54 55 56

fillForm.jsp : 1 2 3 4 5 6 7 8 9
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> </head> <body> <h2>Application form for MTNL Broadband Connection</h2>

<form:form method="POST"> 10 <table> 11 <tr> 12 <td>User Name :</td> 13 <td><form:input path="userName" /></td> </tr> 14 <tr> 15 <td>Address :</td> 16 <td><form:textarea path="address" /></td> 17 </tr> 18 <tr> <td>Sex :</td> 19 <td><form:radiobutton path="sex" value="M" />Male 20 <form:radiobutton 21 path="sex" value="F" />Female</td> 22 </tr> 23 <tr> 24 <td>Select a Plan :</td> 25 <td><form:select path="plan"> 26 <form:option value="NONE" label="-Select Plan-" /> 27 <form:options items="${availablePlans}" /> 28 </form:select> </td> 29 </tr> 30 <tr> 31 <td>Other Options :</td> 32 <td><form:checkboxes items="${availableOptions}" 33path="options" delimiter=" " /> 34 </td> 35 </tr> 36 <tr> 37 <td><input type="submit" /></td> </tr> 38 </table> 39 </form:form> 40 41</body> 42</html> 43 44 45 46 47 48 49

viewForm.jsp :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title></title> </head> <body> <h2>You have applied successfully</h2> <table bgcolor="skyblue"> <tr> <td>User Name :</td> <td>${modelDataToRender.userName}</td> </tr> <tr> <td>Address :</td> <td>${modelDataToRender.address}</td> </tr> <tr> <td>Sex :</td> <td>${modelDataToRender.sex}</td> </tr> <tr> <td>Selected Plan :</td> <td>${modelDataToRender.plan}</td> </tr> <tr> <td>Selected Options :</td> <td><c:forEach items="${modelDataToRender.options}" var="opt"> { <c:out value="${opt}" /> } </c:forEach></td> </tr> </table> <a href="http://localhost:8080/Spring_SimpleFormController/fillFormProc ess.dev">Click here to apply again</a> </body> </html>

To run this example download code , import it into eclipse and configure Tomcat server in eclipse.

Why to override formBackingObject method in Spring MVC ?


You should override formBackingObject(HttpServletRequest request) if you want to provide view with model object data so that view can be initialized with some default values e.g. Consider in your form view there are three text boxes along with other components like text boxes, radio buttons and you want when this form is shown to user two of three check boxes get checked/selected by default. For this you need to override the formBackingObject method. In

this method you can create model object with default values and then return model object containing default values to the view. MtnlModel.java : 1 package com.thecafetechno; 2 public class MtnlModel { public String userName; 3 public String address; 4 public String sex; 5 public String plan; 6 public String [] options; 7 public String getUserName() { 8 return userName; 9 } 10 11 public void setUserName(String userName) { 12 this.userName = userName; 13 } 14 public String getSex() { 15 return sex; 16 } 17 18 public void setSex(String sex) { 19 this.sex = sex; 20 } 21 public String getPlan() { 22 return plan; 23 } 24 25 public void setPlan(String plan) { 26 this.plan = plan; } 27 28 public String getAddress() { 29 return address; 30 } 31 32 public void setAddress(String address) { 33 this.address = address; } 34 35 public String[] getOptions() { 36 return options; 37 } 38 39 public void setOptions(String[] options) { this.options = options; 40 } 41 42 43}

44 45 46 47 48 49 Index.html : 1 2 3 4 5 6 7 8 9 1 0 1 1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1> Welcome to MTNL Delhi</h1> <a href="http://localhost:8080/Spring_SimpleFormController/fillFormProcess.dev" >Click here to apply for fresh MTNL Broadband Connection</a> </body> </html>

web.xml : 1 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" 6 version="2.5"> 7 <display-name>Spring Web MVC Application</display-name> 8 9 <servlet> 10 <servlet-name>dispatcher</servlet-name> <servlet11 class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 12 <load-on-startup>1</load-on-startup> 13 </servlet> 14 15 <servlet-mapping> 16 <servlet-name>dispatcher</servlet-name> <url-pattern>*.dev</url-pattern> 17 </servlet-mapping> 18 19 <context-param> 20 <param-name>contextConfigLocation</param-name> 21 <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>

22 </context-param> 23 24 <listener> <listener-class> 25 org.springframework.web.context.ContextLoaderListener 26 </listener-class> 27 </listener> 28 29 <welcome-file-list> <welcome-file>index.html</welcome-file> 30 </welcome-file-list> 31</web-app> 32 33 34 dispatcher-servlet.xml : 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <value> fillFormProcess.dev = processApplicationFormController </value> </property> </bean> <bean id="processApplicationFormController" class="com.thecafetechno.ProcessApplicationFormController"> <property name="formView" value="fillForm" /> <property name="successView" value="viewForm" /> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewReso lver"> <property name="prefix"> <value>/WEB-INF/jspViews/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>

0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 ProcessApplicationFormController : ProcessApplicationFormController extends SimpleFormController So inherits the form submission capabilities. Overridden onSubmit method is invoked when submit button is clicked on fillForm.jsp. It returns a ModelAndView object containing viewForm.jsp (getSuccessView()) as view and modelDataToRender as model. Overridden referenceData() method is used to provide some additional information to the formView (fillForm.jsp) to display the view e.g. availableOptions and availablePlans in this case. Overridden formBackingObject method is used to provide view with model object so that view can be initialized with some default values e.g. model object mtnlModel contains Modem and Landline set as default values for instance variable options of MtnlModel class, this model object is used by Spring to initialize the formView (fillForm.jsp) with default values (Modem and Landline set checkboxes as checked by default). 1 package com.thecafetechno; 2 3 import java.util.ArrayList; import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 org.springframework.validation.BindException; 10import import org.springframework.web.servlet.ModelAndView; 11import org.springframework.web.servlet.mvc.SimpleFormController; 12 13public class ProcessApplicationFormController extends SimpleFormController {

14 public ProcessApplicationFormController() { 15 setCommandClass(MtnlModel.class); 16 } 17 18 @Override 19 protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException 20 21errors) throws Exception { 22 23 MtnlModel mtnlModel = (MtnlModel)command; 24 return new 25ModelAndView(getSuccessView(),"modelDataToRender",mtnlModel); } 26 27 @Override 28 protected Map<String, List<String>> referenceData(HttpServletRequest 29request) throws Exception { 30 List<String> listOfOptions = new ArrayList<String>(); listOfOptions.add("Modem"); 31 listOfOptions.add("Extra cable"); 32 listOfOptions.add("Landline set"); 33 34 List<String> listOfPlans = new ArrayList<String>(); 35 listOfPlans.add("Rs:399"); 36 listOfPlans.add("Rs:599"); listOfPlans.add("Rs:799"); 37 listOfPlans.add("Rs:999"); 38 Map<String, List<String>> map = new HashMap<String, List<String>>(); 39 map.put("availablePlans", listOfPlans); 40 map.put("availableOptions", listOfOptions); 41 return map; } 42 43 @Override 44 protected Object formBackingObject(HttpServletRequest request) throws 45Exception { 46 String[] options = {"Modem","Landline set"}; MtnlModel mtnlModel = new MtnlModel(); 47 mtnlModel.setOptions(options ); 48 return mtnlModel; 49 } 50 51} 52 53 54 55 56 fillForm.jsp :

1 2 3 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 4 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 5 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 6 <html> 7 <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 8 </head> 9 <body> 10 <h2>Application form for MTNL Broadband Connection</h2> 11 <form:form method="POST"> 12 <table> 13 <tr> 14 <td>User Name :</td> 15 <td><form:input path="userName" /></td> </tr> 16 <tr> 17 <td>Address :</td> 18 <td><form:textarea path="address" /></td> 19 </tr> 20 <tr> <td>Sex :</td> 21 <td><form:radiobutton path="sex" value="M" />Male 22 <form:radiobutton 23 path="sex" value="F" />Female</td> 24 </tr> 25 <tr> 26 <td>Select a Plan :</td> 27 <td><form:select path="plan"> 28 <form:option value="NONE" label="-Select Plan-" /> 29 <form:options items="${availablePlans}" /> 30 </form:select> </td> 31 </tr> 32 <tr> 33 <td>Other Options :</td> 34 <td><form:checkboxes items="${availableOptions}" 35path="options" delimiter=" " /> 36 </td> 37 </tr> 38 <tr> 39 <td><input type="submit" /></td> </tr> 40 </table> 41 </form:form> 42 43</body> 44</html> 45 46

47 48 49 viewForm.jsp : 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title></title> </head> <body> <h2>You have applied successfully</h2> <table bgcolor="skyblue"> <tr> <td>User Name :</td> <td>${modelDataToRender.userName}</td> </tr> <tr> <td>Address :</td> <td>${modelDataToRender.address}</td> </tr> <tr> <td>Sex :</td> <td>${modelDataToRender.sex}</td> </tr> <tr> <td>Selected Plan :</td> <td>${modelDataToRender.plan}</td> </tr> <tr> <td>Selected Options :</td> <td><c:forEach items="${modelDataToRender.options}" var="opt"> { <c:out value="${opt}" /> } </c:forEach></td> </tr> </table> <a href="http://localhost:8080/Spring_SimpleFormController/fillFormPro cess.dev">Click here to apply again</a> </body> </html>

To run this example download code , import it into eclipse and configure Tomcat server in eclipse.

What are the advantages of Spring MVC over Struts MVC ?


1. There is clear separation between models, views and controllers in Spring. 2. Springs MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance. 3. Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests. 4. Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface. 5. In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy. 6. Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet. 7. Spring web layer built on top of a business object layer which is considered a good practice. In Struts framework you need to implement your business objects . 8. Struts forces your Controllers to extend a Struts class but Spring doesnt, there are many convenience Controller implementations that you can choose to extend. 9. In struts a variety of Struts specific tags are used to assure that request parameters are bound to ActionForm fields and show binding/validation errors. In SpringMVC, there is one simple bind tag that handles all of this. Your JSPs remain smaller and have more pure HTML content. 10. In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality. 11. With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database

FileSystemResource vs ClassPathResource [Differentiate FileSystemResource and ClassPathResource ]


Difference between FileSystemResource and ClassPathResource: In FileSystemResource you need to give path of spring-config.xml (Spring Configuration) file relative to your project or the absolute location of the file. You can get this by right-clicking the spring-config.xml in eclipse project explorer, select properties and copy the path value (excluding name_of_your_project/) from properties window and use it in FileSystemResource. See figure :

In ClassPathResource spring looks for the file using ClassPath so spring-config.xml should be included in classpath. If spring-config.xml is in src so we can give just its name because src is in classpath path by default. Note: We usually get difficulties in giving path to spring xml configuration file so do practice by putting the config file in different locations. If in our project we put the spring-config.xml in src/com.thecafetechno then our FileSystemResource would be: 1FileSystemResource("src/com/thecafetechno/spring-config.xml"); And ClassPathResource would be: 1config.xml");
ClassPathResource resource = new ClassPathResource("com/thecafetechno/springFileSystemResource resource = new

BeanFactroy vs ApplicationContext ?[Difference between BeanFactory and ApplicationContext]


BeanFactory Instantiates beans lazily i.e. Beans are instantiated when you get them from BeanFactory not on loading BeanFactory. BeanFactory beanFactory = new XMLBeanFactory(new ClassPathResource(springbeans.xml)); // factory is loaded Emp emp = beanFactory.getBean(empBean); // bean is instantiated No support for Message Internationalization (i18n) No event handling (event propagation). Access to low level resources is not convenient in BeanFactory. Can resolve text messages according to locale, supports Message Internationalization (i18n) ApplicationContext

Instantiates beans eagerly i.e. Beans are instantiated when ApplicationContext is loaded/up. ApplicationContext appCtx = new ClassPathXmlApplicationContext(spring-beans.xml); // bean instantiated and ApplicationContext is up.

Provides event-propagation to the beans which are registered as listener to ApplicationContext i.e. beans implementing ApplicationListener interface. Access is very convenient. Application contexts has a generic/common way to load file resources. resource loader, can load resources including FileSystemResource. ClassPathResource ServletContextResource InputStreamResource

How to customize bean destruction process ? [ controlling bean destruction]


The Spring offers several callback interfaces to modify the behaviour of your bean. By implementing DisposableBean interface Spring Container will call destroy() method just before the container is destroyed. This can be achieved by following two ways (a) Implemet DisposableBean interface and provide implementation of destroy() method. 1<bean id="testBeanId" class="example.TestBean "/> public class TestBean implements DisposableBean { public void destroy() { // do cleanup task } } (b) Usually the above described way of customizing the bean initialization process is avoided as it forces our bean class to implement an interface (DisposableBean) thus couples the client code to Spring Container. Same thing can be achieved by using init-method attribute of bean tag in Spring configuration file as given below. 1<bean id="testBeanId" class="example.TestBean " destroy-method="cleanup"/> public class TestBean { public void cleanup() { // do cleanup task } }

How to customize bean initialization process ? [ controlling bean initialization] Initialization callbacks, Lifecycle callbacks, InitializingBean, afterPropertiesSet(), init-method
The Spring offers several callback interfaces to modify the behaviour of your bean. By implementing InitializingBean interface Spring Container will call afterPropertiesSet() method to allow the bean to perform certain initialization tasks after all properties on the bean have been injected by the container . This can be achieved by following two ways (a) Implemet InitializingBean interface and provide implementation of afterPropertiesSet() method.

1<bean id="testBeanId" class="example.TestBean "/> public class TestBean implements InitializingBean { public void afterPropertiesSet() { // do initialization task } } (b) Usually the above described way of customizing the bean initialization process is avoided as it forces our bean class to implement an interface (InitializingBean) thus couples the client code to Spring Container. Same thing can be achieved by using init-method attribute of bean tag in Spring configuration file as given below. 1<bean id="testBeanId" class="example.TestBean " init-method="init"/> public class TestBean { public void init() { // do initialization task } }

How to implement inheritance in Bean definition ? What is the use of parent attribute in Spring Bean ?
Inheritance can be implemented by specifying the parent attribute in bean and passing id of (parent) bean that you want to inherit . In the example below Employee bean inherits properties(name, age, sex) of Person bean, no need to specify these properties in child bean (Employee). 1 <!--?xml version="1.0" encoding="UTF-8"?--> xmlns="http://www.springframework.org/schema/beans" 2 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://www.springframework.org/schema/beans 4 5 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 6 <bean id="personBean" class="com.thecafetechno.Person"> 7 <property name="name" value="Davinder"/> 8 <property name="age" value="24"/> 9 <property name="sex" value="male"/> 10 </bean> <bean id="employeeBean" class="com.thecafetechno.Employee" 11 parent="personBean"> 12 <property name="company" value="thecafetechno.com"/> 13 <property name="address" ref="addressBean"/> 14 </bean> 15 <bean id="addressBean" class="com.thecafetechno.Address">

<property name="city" value="Hoshiarpur"/> 16 <property name="state" value="Punjab"/> 17 </bean> 18</beans> 19 20 21

To run this example download code , import it into eclipse and configure build path by adding jars to classpath.

Explain Inner Bean in Spring ?


A bean which is defined (embedded) inside the property tag of other bean is called an inner bean. Inner beans can not be used (referred) by other beans except the enclosing one. In following configuration addressBean is an inner bean as it is defined inside the property tag of employeeBean. 1 2 <!--?xml version="1.0" encoding="UTF-8"?--> xmlns="http://www.springframework.org/schema/beans" 3 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 7 <bean id="employeeBean" class="com.thecafetechno.Employee" 8 parent="personBean"> 9 <property name="company" value="thecafetechno.com"/> 10 <property name="address"> 11 <bean id="addressBean" class="com.thecafetechno.Address"> <property name="city" value="Hoshiarpur"/> 12 <property name="state" value="Punjab"/> 13 </bean> 14 </property> 15 </bean> 16</beans> 17

What is Dependency Injection in Spring ?


Answer : In spring objects define their associations (dependencies) and do not worry about how to get those dependencies ; now it is the responsibility of Spring to provide the required dependencies for creating objects. Spring creates the dependent objects and injects those object into the bean. Suppose we have an object Employee and it has a dependency on object Address. So we define a bean corresponding to Employee where it will define its dependency on object Address. When Spring try to create an Object Employee it sees that Employee has a dependency on object

Address so first it will create the Address object (dependent object) and then inject this into the Employee Object. Given below is the xml configuration for injecting addressBean into the employeeBean using setter injection. To see complete example of DI click here. 1 2<bean id="employeeBean" class="com.thecafetechno.Employee"> <property name="name" value="Davinder"/> 3 <property name="age" value="24"/> 4 <property name="address" ref="addressBean"/> 5</bean> 6<bean id="addressBean" class="com.thecafetechno.Address"> <property name="city" value="Hoshiarpur"/> 7 <property name="state" value="Punjab"/> 8</bean> 9

What is Inversion of Control in spring ?


Answer : IOC means inverting the control of creating the object from our own using new operator to Spring container. Inversion of Control (also known as dependency injection) says you are not supposed to create application objects but describe how they should be created in a configuration file. To connect components with services just describe which service is needed by which component rather than directly connecting them. Inversion of Control (IOC) and Dependency Injection are used interchangeably. IOC is achieved through DI. DI is the process of providing the dependencies of an object and IOC is the end result of DI. By DI the responsibility of creating objects is shifted from our application code to Spring container hence the phenomenon is called Inversion of Control (IOC). Question: What are different types of injection in Spring ? Ans: Three types of injection in Spring3 Framework (1) Setter Injection (2) Constructor Injection (3) Getter or Method Injection

Benefits of using Spring Framework ?


Answer :

Spring is relatively light weight container in comparison to other J2EE containers. It does not use much memory and CPU cycles for loading beans, providing services like transaction control , AOP management, JDBC interaction.

Spring makes it easy to develop J2EE application as it has built-in support for WEB MVC framework. Spring helps creating loosely coupled applications by DI. Spring has no dependency on any application servers. Spring creates objects lazily which helps in developing light weight applications. Spring supports aspect oriented programming to manage logging, transaction, security etc. Spring makes Database interaction (operations) easier as it has support for data access techniques such as DAO, JDBC, Hibernate, IBATIS, JDO etc. With the help of spring application code can be unit tested easily as Spring provides unit testing support classes. Spring does not need unique deployment steps. Spring configuration is done in standard XML format which easy to write and understand.

Describe different modules of Spring Framework


Answer : Spring comprises of the following modules. Core container : Basic functionality of Spring is provided by the core container. BeanFactory is the primary component of core container, an implementation of the Factory design pattern. The BeanFactory applies the Inversion of Control (IOC) pattern so that applications configuration and dependency specification can be separated from the actual application code. Spring context : Context module is built on the base core container. The Context module inherits features of Beans module. It has support for internationalization , eventpropagation, resource-loading. It also supports Java EE features such as EJB, JMX and basic remoting. Spring AOP : The Spring AOP module provides aspect-oriented programming functionality into the Spring framework. We can apply AOP to any object managed by the Spring framework. Declarative transaction management can be applied into your application by using Spring AOP. Spring DAO : The Spring DAO makes it easy to work with different database techniques like JDBC, ORM, OXM etc. It provides meaningful exception hierarchy for managing the exceptions and error messages thrown by vendor specific database. Spring ORM : The Spring ORM module supports different ORM tools like JPA, JDO, Hibernate, and iBatis. We can use all of these O/R-mapping frameworks in combination with other features offered by Spring. Spring Web module : Springs Web package provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container

using servlet listeners and a web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with. Spring MVC framework : Spring MVC module provides a full-featured MVC implementation for building Web applications.

What is BeanFactory ?

BeanFactory ( org.springframework.beans.factory.BeanFactory an interface) acts as Spring IoC container that is responsible for containing, configuring and managing the application beans. BeanFactory is the contract defined for Spring managed beans and all the beans managed by Spring implements this interface by default. It is the central IoC container interface in Spring Framework. There are a many implementations of the BeanFactory interface. XmlBeanFactory class is most common implementation of BeanFactory. This implementation helps to define your application objects and dependencies between such objects, in terms of XML format. The XmlBeanFactory requires XML metadata and uses it to generate a fully configured system ready to use.

What is XmlBeanFactory ?
Answer : There are a many implementations of the BeanFactory interface. XmlBeanFactory class is most common implementation of BeanFactory. This implementation helps to define your application objects and dependencies between such objects, in terms of XML format. The XmlBeanFactory requires XML metadata and uses it to generate a fully configured system ready to use. XmlBeanFactory extends DefaultListableBeanFactory and defines two constructors.

What is ApplicationContext ?
Answer : ApplicationContext ( org.springframework.context.ApplicationContext ) is an interface which makes Spring a framework. It is derivd from BeanFactory, so has all the functionality of BeanFactory and adds lots more. Like BeanFactory it is responsible for containing, configuring and managing the application bean. In addition to this it provides following framework oriented functionality

MessageSource, provide support for internationalization (I18N) messages . Access to resources, such as URLs and files. Event propagation for beans which implements the ApplicationListener interface. Loading of multiple (hierarchical) contexts Enterprise services like EJB integration ,JNDI,remoting and scheduling

What are the common implementations of the Application Context ?

There are three most commonly used implementation of Application Context as ClassPathXmlApplicationContext : It loads the context definition from an XML file present in the classpath, treating context definitions as classpath resources. Given below is the code for loading context from classpath. File beans.xml should be present in classpath of application. ApplicationContext appContext = new ClassPathXmlApplicationContext(beans.xml); FileSystemXmlApplicationContext : It loads the context definition from an XML file present in the filesystem. Need to give absolute path of the file beans.xml as given below : ApplicationContext appContext = new FileSystemXmlApplicationContext(F:/java_program/SpringProject/src/com/thecafetechno/beans.xml); XmlWebApplicationContext : It loads the context definition from an XML file present within a web application.

What is Bean wiring ?


The process of linking (associating) beans with each other within a Spring container is called bean wiring. All the Spring managed beans of the application needs to be defined in an xml file. A bean may have dependency on the other bean. So these two beans are to be linked with each other and the process of linking beans is called bean wiring. Given below are two beans and addressBean is wired (linked) with employeeBean. 1 2<bean id="employeeBean" class="com.thecafetechno.Employee"> <property name="name" value="Davinder"/> 3 <property name="age" value="24"/> 4 <property name="address" ref="addressBean"/> 5</bean> 6<bean id="addressBean" class="com.thecafetechno.Address"> <property name="city" value="Hoshiarpur"/> 7 <property name="state" value="Punjab"/> 8</bean> 9

What is auto wiring ?


The Spring container provides the functionality of connecting beans with each other automatically called autowiring . Rather we inject one bean into the other using ref attribute, Spring can look into the BeanFactory and decide how to inject one bean into the other. So we dont explicitly connect (wire) beans instead spring does this for us. Autowiring helps to minimize the need to specify properties or constructor arguments, thus saves a lot of typing . Autowiring is specific to individual beans, a bean may or may not use aotuwiring. To enable autowire for a bean, autowire attribute is use inside tag. There are five types of autowiring : 1. 2. 3. 4. 5. no (default) byName byType constructor autodetect

addressBean is autowired with employeeBean using autowire=byType mode. 1 2 <bean id="employeeBean" class="com.thecafetechno.Employee" autowire=byType> <property name="name" value="Davinder"/> 3 <property name="age" value="24"/> 4 <!-5 Because of autowiring third property is not needed to be defined 6 <property name="address" ref="addressBean"/> --> 7 8 </bean> <bean id="addressBean" class="com.thecafetechno.Address"> 9 <property name="city" value="Hoshiarpur"/> 10 <property name="state" value="Punjab"/> 11</bean> 12

What are the different bean scopes in Spring ? Explain with an example ?
In Spring, creation of beans can be controlled by defining the scope of bean. To define scope attribute scope of <bean> tag is used. There are five types of bean scopes in Spring

singleton prototype request session global session

An Introduction to Spring AOP


AOP Module of Spring provides aspect-oriented programming features and has built in support for AOP (aspect-oriented programming). In AOP program logic is divided into different parts called concerns. Consider an application having different modules e.g. Registration , Appointment , Operation etc. as shown below . These modules perform different functionality. Each module has a specific functionality to perform which represents its concern like Registration module performs registration of customers so registration is its concern. But there are some other functionalities (concerns) which are needed in multiple module. The concerns that cut across multiple modules are called cross-cutting concerns like logging , security, data transfer. So to manage these cross-cutting concerns aspect-oriented programing is used otherwise each module need to address these concerns .

In AOP we create aspects which implement cross-cutting functionality. These aspects are hooked into the different modules wherever needed without modifying the existing code base of these modules which is possible by AOP only. This is the biggest advantage of AOP that we can implement functionality on one or more modules without changing implementation of those Modules which is not possible otherwise. Aspect is like triggers in database . In database we can define triggers which perform some functionality on executing some DML statements. Consider a trigger which is executed when some data is inserted into the database and before inserting data it changes characters to capitals. Here we dont modify the actual insertion query to change characters to capitals but triggers do it for us. We will discuss how AOP is implemented later but first we need to understand some concepts of AOP.

AOP Concepts
Concern :

Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement in a module is concern of the module. Issues in which we are interested defines our concerns.
Cross-Cutting Concern :

Its a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns.

Aspect :

Aspect defines the implementation of cross-cutting concern. We implement a cross-cutting functionality by creating an aspect. Aspect encapsulates our cross-cutting concern. There are two ways to define aspects in Spring. One is schema based(regular java class and configuration in spring configuration file ) and other in annotation based (regular java class with annotation @Aspect) . An aspect contains pointcut and advice body.
Advice :

Action performed by an aspect at a particular join point. Different types of advice are around, before ,after, afterreturning and afterthrowing . Advice is linked to pointcut and defines what/how and when to perform the action.
Join point :

Join point represents execution of a method where we want to hook the advice into. Consider execution of a program and during this some methods are called say meth1(), meth2(), meth3(). Now we need to implement some cross-cutting functionality before or after execution of meth2(), this meth2() act as a join point. A join point is referred by a pointcut.
Pointcut :

A pointcut is an expression/predicate which points to a join point. Pointcut defines where to hook the advice. e.g. @Pointcut(execution(* com.thecafetechno.Drive.drive(..))) this pointcut is pointing to the execution of method drive of class com.thecafetechno.Drive . Pointcut is associated with an advice.
Target Object :

Object being guided by the advice . Object to which we hook our advices is called target object. Spring creates proxy of target object to implement Aspect behavior.
AOP proxy :

AOP framework of Spring creates dynamic objects to implement the cross-cutting functionality, these objects are called AOP proxy . Proxy is an object created after applying advice to target object.
Weaving :

Binding of objects and aspects to create an advised object is called weaving. This binding can be done at runtime in Spring AOP framework.

Pictorial Representation of AOP :

Different Type of advices : Before advice :

Before advice executes before a join point (target method on which we hooked the advice) matched by pointcut.
After returning advice :

This advice executes after a join point (target method) is executed successfully i.e. join point is executed without throwing any exception.
After throwing advice :

This advice executes if join point (target method) exits by throwing any exception.
After (finally) advice :

This advice executes after a join point (target method) is completed regardless of exception occurred or not. This advice is guaranteed to be executed whether target method executes normally or executes with exception.

Around advice :

This advice is combination of before and after advices. It lets you do something before a join point and some other things after the join point. Around advice surrounds the join point.

Spring Proxying Mechanisms


Spring AOP framework uses proxying mechanism to generate dynamic proxies of target objects so that advices can be applied to the target objects being advised. There are two ways to create proxies (1) By using JDK dynamic proxies (2)By using CGLIB to generate proxies The choice depends whether target object implements any interface , if yes then JDK dynamic proxies are used and Spring uses the JDKs java.lang.reflect.Proxy class to generate new dynamic proxy class which implements the interfaces of the target object. This proxy wraps the target class, perform the advice functionality and then invoke target method.See fig below.

If Target object does not implement any interface then CGLIB proxies are used. Using CGLIB Spring generates a subclass of the target class and binds the advices and finally propagates

method call to target class.(CGLIB jar is required). See fig below.

JDK proxies versus CGLIB proxies :

Using CGLIB has a limitation that methods marked as final in target class cant be advised as final methods cant be overridden (CGLIB creates a subclass of target class at runtime) but this limitation disappears in case of using JDK dynamic proxies. Using CGLIB is favored when dealing with legacy code where target classes do not implement any interfaces. JDK proxy mechanism leads to loosely coupled application because interfaces of target class are used in generating proxies. JDK dynamic proxies are favored over CGLIB. Constructor of your proxied object is called twice in CGLIB proxies but not in JDK proxies

We can tell Spring to use CGLIB to create proxies, set proxy-target-class attribute to true : <aop:config proxy-target-class=true> In case of @AspectJ style, set the proxy-target-class attribute to true: <aop:aspectj-autoproxy proxy-target-class=true/>.

Spring AOP Example


Annotation based @Aspectj style (Autoproxying)

In this example we used annotation based AOP. Jar files required for this project are listed below. aspectjweaver-1.6.1.jar , commons-logging-1.1.jar, guice-aopalliance.jar, spring-aop-3.0.2.RELEASE.jar,spring-asm-3.0.2.RELEASE.jar, spring-beans-

3.0.6.RELEASE.jar, spring-context-3.0.6.RELEASE.jar,spring-core-3.0.2.RELEASE.jar, spring-expression3.0.5.RELEASE.jar To download required jars click here . Project structure is shown in figure below.

DriverInterface.java :

Spring AOP framework creates proxy of the target objects. We need to define an interface of target class since this interface will be used to create proxy of the target class. To see Spring proxy mechanism click here
1package com.thecafetechno; 2public interface DriverInterface { 3 4} Driver.java :
public void drive(boolean flag) throws Exception;

This is the target class whose objects will be advised. This class has a public method drive which act as join point. Some additional functionality will be implemented before or after the execution of this join point by advices defined in Aspect. From main we just call this method and advices will run automatically by Spring AOP framework.
1 package com.thecafetechno;

2 public class Driver implements DriverInterface{ 3 4 5 6


throw new Exception(); public void drive(boolean flag) throws Exception{ System.out.println("Driver is driving the car"); if(!flag){ System.out.println("Driver made mistake");

7 8 9 } 10
}

DrivingGuidelines.java :

It is the Aspect containing Advices and Pointcut to advise the target objects. It contains the cross-cutting concerns implementation in the form of advice bodies. First we have defined a pointcut which is pointing to the execution of method drive(join point) of target class Drive as @Pointcut(execution(public void com.thecafetechno.Driver.drive(boolean))) public void pointcutForDrive() {} The pointcut above defined by @Pointcut notation is represented by a marker method defined just below it called the pointcut signature. This marker method refers to the associated pointcut and is used in defining Advices. We have defined some advices (before,after,around ect) according to our requirement.All advices having advice body defining what action to perform. In around advice the statement pjp.proceed(); invokes the target method (drive).This advice body takes an argument of type ProceedingJoinPoint. The advice body contains statements , some of which are executed before the target method and some are executed after the target method.
1 package guideline; 2 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.After; 5 import org.aspectj.lang.annotation.AfterReturning; 6 import org.aspectj.lang.annotation.AfterThrowing;

7 import org.aspectj.lang.annotation.Around; 8 import org.aspectj.lang.annotation.Aspect; 9


import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut;

10 11

@Aspect

12
public class DrivingGuidelines {

13 14 15 16 17 18 19
// before advice // Pointcut expression pointing to execution of drive method

@Pointcut("execution(public void com.thecafetechno.Driver.drive(boolean))") public void pointcutForDrive(){} //pointcut signature,a marker method //used in defining advices

20 21 22 23 24 25 26 27 28 29

@Before("pointcutForDrive()") public void takeDrivingLicence() { System.out.println("Before Advice : Driver takes the Licence"); }

// Around advice @Around("pointcutForDrive()") public void putSeatBelt(ProceedingJoinPoint pjp) throws Throwable { System.out.println("Around Advice : Driver puts seat belt"); pjp.proceed(); //invokes the target method System.out.println("Around Advice : Driver reached destination

30safely"); 31
}

32 33 34 35 36
} // AfterReturning advice @AfterReturning("pointcutForDrive()") public void lockCar() { System.out.println("AfterReturning Advice : Driver locks the car");

37 38
// AfterThrowing advice

39 40 41 42 43 44 45 46 47 48 49 50 51

@AfterThrowing("pointcutForDrive()") public void accident() { System.out.println("AfterThrowing Advice : Accident Encountered"); }

// After advice @After("pointcutForDrive()") public void endOfDriving() { System.out.println("After Advice : Driving Finished");

TestDrive.java :

It is our main class. Here we created the target object driver and using this invoked the target method drive. drive method is called by passing a boolean argument true/flase represent successful/unsuccessful drive. To instantiate the Spring container ClassPathXmlApplicationContext is used.
1 package main;

2 import org.springframework.beans.factory.BeanFactory; 3 import org.springframework.context.ApplicationContext; 4 5 6


public class TestDrive { import org.springframework.context.support.ClassPathXmlApplicationContext; import com.thecafetechno.DriverInterface;

7
public static void main(String[] args) {

ApplicationContext context = new 9 ClassPathXmlApplicationContext("beans.xml");

10

BeanFactory factory= context; DriverInterface driver=(DriverInterface)

11factory.getBean("driverBean"); 12 13 14 15 16 17
} } try{

driver.drive(true); }catch (Exception e) { }

beans.xml :

In this configuration file we have used element <aop:aspectj-autoproxy /> to enable spring Suport for @Aspectj aspects and autoproxying. If spring finds that its bean is advised by some aspects then it creates a proxy of that bean to implement the Aspect behavior
1 2
xmlns:aop="http://www.springframework.org/schema/aop" <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

3 4 5

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

6 7 http://www.springframework.org/schema/aop 8 9 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 10 11 12 13
</beans> <aop:aspectj-autoproxy /> <bean name="driverBean" class="com.thecafetechno.Driver"/> <bean name="guidelinesBean" class="guideline.DrivingGuidelines"/>

14 15 OutPut :

(a) When method drive is called with argument true Before Advice : Driver takes the Licence Around Advice : Driver puts seat belt Driver is driving the car Around Advice : Driver reached destination safely AfterReturning Advice : Driver locks the car After Advice : Driving Finished (b) When method drive is called with argument false Before Advice : Driver takes the Licence Around Advice : Driver puts seat belt Driver is driving the car Driver made mistake AfterThrowing Advice : Accident Encountered After Advice : Driving Finished (c) If we eliminate <aop:aspectj-autoproxy /> element from beans.xml, Spring will not be able to generate proxy of target object so no advices will run, only target method executes.(method drive is called with argument true) Driver is driving the car To run this example download code , import it into eclipse and configure build path by adding jars to classpath.

Schema based (Autoproxying)

This schema based example is same as the previous annotation based example just two files are modified. To see previous example click here. (1) DrivingGuidelines.java (2) beans.xml Source code of these files is given below.
DrivingGuidelines.java :

It is a regular java class containing some methods. All the annotations are removed and no pointcut is defined unlike annotation based class.
1 package guideline; 2 3 4
public void takeDrivingLicence() { import org.aspectj.lang.ProceedingJoinPoint; public class DrivingGuidelines {

5
System.out.println("Before Advice : Driver takes the Licence");

6 7 8 9 10 11 12 13 14 15 16 17

public void putSeatBelt(ProceedingJoinPoint pjp) throws Throwable { System.out.println("Around Advice : Driver puts seat belt"); pjp.proceed(); //invokes the target method

System.out.println("Around Advice : Driver reached destination safely"); }

public void lockCar() { System.out.println("AfterReturning Advice : Driver locks the car"); }

18 19 20 21 22 23

public void accident() { System.out.println("AfterThrowing Advice : Accident Encountered"); }

public void endOfDriving() { System.out.println("After Advice : Driving Finished"); }

24 25 26

beans.xml :

This xml file is quite different than the one used for annotation based AOP. It contains the bean definition for the target bean(driverBean) as well as for aspect bean(guidelinesBean). To implement AOP <aop:config> tag is used. All the aspects are defined within this tag. Aspect is defined by <aop:aspect> , ref attribute here refers to the bean definition of aspect. Inside aspect pointcut is defined using <aop:pointcut>, expression attribute points to the execution of some join-points/method/methods(method drive in this case) and id attribute is used as unique identifier to refer to this pointcut. Advices are defined by specifying type of advice, method attribute specifies which method of aspect to invoke when a particular join point is executed referred by pointcut-ref attribute.
1 2 3
xsi:schemaLocation="http://www.springframework.org/schema/beans <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"

4 5 6 7 8 9 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
http://www.springframework.org/schema/aop http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

10 11 12 13 14
<bean name="driverBean" class="com.thecafetechno.Driver"/> <bean name="guidelinesBean" class="guideline.DrivingGuidelines"/> <aop:config> <aop:aspect ref="guidelinesBean"> <aop:pointcut id="performance" expression="execution(public void

15com.thecafetechno.Driver.drive(boolean))" /> 16 17 18 19
/> <aop:after-throwing method="accident" pointcut-ref="performance" <aop:before method="takeDrivingLicence" pointcutref="performance" /> <aop:around method="putSeatBelt" pointcut-ref="performance" /> <aop:after-returning method="lockCar" pointcut-ref="performance"

20/> 21 22 23

<aop:after method="endOfDriving" pointcut-ref="performance" /> </aop:aspect> </aop:config>

24</beans>

AOP using DefaultAdvisorAutoProxyCreator : (Autoproxying)

This AOP example is having the same project structure and jars required as the previous examples. It explains the use of Springs DefaultAdvisorAutoProxyCreator class. Two files we have modified which are given below : beans.xml : DefaultAdvisorAutoProxyCreator class creates proxy for the class whose methods are matched with the pattern (.*drive) specified by RegexpMethodPointcutAdvisor bean. Instead of RegexpMethodPointcutAdvisor we can also use AspectJExpressionPointcutAdvisor as given in the commented out code below.
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:aop="http://www.springframework.org/schema/aop"

4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 7 8 9 1 0 1 1 1 2
<bean http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> http://www.springframework.org/schema/aop

<bean name="driverBean" class="com.thecafetechno.Driver"/> <bean name="guidelinesBean" class="guideline.DrivingGuidelines"/>

1 class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCr 3 eator" /> 1 4 1 5 1 6 1 7


<!--

<bean id="driveInterceptor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice" ref ="guidelinesBean"/> <property name="pattern" value=".*drive"/> </bean>

1 8 1 9 2 0

<bean id="driveInterceptor" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor"> <property name="advice" ref ="guidelinesBean"/> <property name="expression" value="execution(* *.drive(..))"/> </bean> -->

2 1 </beans>

2 2 2 3 2 4 2 5 2 6 2 7 2 8

DrivingGuidelines.java :
1 package guideline; 2 import java.lang.reflect.Method; 3 4 5
import org.springframework.aop.MethodBeforeAdvice; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.AfterReturningAdvice;

6 7 8 9

import org.springframework.aop.ThrowsAdvice;

public class DrivingGuidelines implements MethodInterceptor, MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {

10 11 12
public void before(Method method, Object[] args, Object target) throws Throwable {

13 14 15 16 17 18
}

System.out.println("Before Advice : Driver puts seat belt");

public Object invoke(MethodInvocation mi) throws Throwable { System.out.println("Around Advice : Driver takes the Licence"); Object obj = mi.proceed(); System.out.println("Around Advice : Driver reached destination

19safely"); 20 21 22 23 24
System.out.println("AfterReturning Advice : Driver locks the car"); public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { } return obj;

25 26 27 28 29 30} 31 32

public void afterThrowing(Throwable throwable) { System.out.println("AfterThrowing Advice : Accident Encountered"); }

AOP using BeanNameAutoProxyCreator :

This AOP example is having the same project structure and jars required as the previous examples. It explains the use of Springs BeanNameAutoProxyCreator class. We are specifying the name of interfaces whose proxies will be created by Spring unlike previous examples of AOP. beans.xml : BeanNameAutoProxyCreator class creates proxy for the interfaces listed as the value of beanNames property. RegexpMethodPointcutAdvisor is used to define the pattern of

methods (pointcut) to be matched and advices to be applied. Instead of RegexpMethodPointcutAdvisor we can also use AspectJExpressionPointcutAdvisor as given in the commented out code below.
<beans xmlns="http://www.springframework.org/schema/beans"

1
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

2 3 4

xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans

5 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 6 7 http://www.springframework.org/schema/aop 8 9 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 1 0 1 1 1 2

<aop:aspectj-autoproxy/> <bean name="driverBean" class="com.thecafetechno.Driver"/> <bean name="guidelinesBean" class="guideline.DrivingGuidelines"/>

<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" 1 >

3 1 4 1 5 1 6 1 7 1

<property name="beanNames"> <list> <value>com.thecafetechno.DriverInterface</value> </list> </property> <property name="interceptorNames"> <list> <value>driveInterceptor</value> </list>

8 1 9

</property> </bean>

2 <bean id="driveInterceptor" 0 class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> 2 1 2 2 2 3 2 4 2 5 2 6 </beans> 2 7 2 8 2 9 3 0 3 1 3 2 3 3


--> <property name="advice" ref ="guidelinesBean"/> <property name="pattern" value=".*drive"/> </bean> <!-<bean id="driveInterceptor" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor"> <property name="advice" ref ="guidelinesBean"/> <property name="expression" value="execution(* *.drive(..))"/> </bean>

3 4 3 5 3 6 3 7 3 8

DrivingGuidelines.java :
package guideline;

1
import java.lang.reflect.Method;

2 3

import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation;

4 import org.springframework.aop.AfterReturningAdvice; 5 import org.springframework.aop.MethodBeforeAdvice; 6 import org.springframework.aop.ThrowsAdvice; 7 8 public class DrivingGuidelines implements MethodInterceptor, 9 10 11 12 13
} public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("Before Advice : Driver puts seat belt"); MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {

14 15
public Object invoke(MethodInvocation mi) throws Throwable {

16 17 18 19 20 21 22 23 24 25 26
} }

System.out.println("Around Advice : Driver takes the Licence"); Object obj = mi.proceed();

System.out.println("Around Advice : Driver reached destination safely"); return obj;

public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("AfterReturning Advice : Driver locks the car");

public void afterThrowing(Throwable throwable) {

27
System.out.println("AfterThrowing Advice : Accident Encountered");

28 29 30 31 32
}

AOP using ProxyFactoryBean :

This AOP example is having the same project structure and jars required as the previous examples. It explains the use of Springs ProxyFactoryBean class. We are specifying the name of interfaces whose proxies will be created by Spring unlike previous examples of AOP. beans.xml : ProxyFactoryBean class creates proxy for the interfaces listed as the value of target property. RegexpMethodPointcutAdvisor is used to define the pattern of methods (pointcut) to be matched and advices to be applied. Instead of RegexpMethodPointcutAdvisor we can also use AspectJExpressionPointcutAdvisor as given in the commented out code below.
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

3 xmlns:aop="http://www.springframework.org/schema/aop" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 6 7 8 9
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> http://www.springframework.org/schema/aop http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

10 11
<aop:aspectj-autoproxy/>

12 13 14 15 16 17 18 19 20

<bean name="driverBean" class="com.thecafetechno.Driver"/> <bean name="guidelinesBean" class="guideline.DrivingGuidelines"/> <bean class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target"> <list> <value>com.thecafetechno.DriverInterface</value> </list> </property> <property name="interceptorNames"> <list>

21 22 23 24 25 26 27

<value>driveInterceptor</value> </list> </property> </bean>

<bean id="driveInterceptor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice" ref ="guidelinesBean"/>

28 29 30 31
<!--

<property name="pattern" value=".*drive"/> </bean>

32class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor"> 33 34 35 36 37 38 39
--> <property name="advice" ref ="guidelinesBean"/> <property name="expression" value="execution(* *.drive(..))"/> </bean>

<bean id="driveInterceptor"

</beans>

DrivingGuidelines.java :
1 package guideline; 2 import java.lang.reflect.Method; 3 4 5 6 7 8 9 10 11
public void before(Method method, Object[] args, Object target) public class DrivingGuidelines implements MethodInterceptor, MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice { import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.aop.ThrowsAdvice;

12 13 14 15 16 17
}

throws Throwable { System.out.println("Before Advice : Driver puts seat belt");

public Object invoke(MethodInvocation mi) throws Throwable { System.out.println("Around Advice : Driver takes the Licence"); Object obj = mi.proceed();

18

System.out.println("Around Advice : Driver reached destination safely"); 19

20 21 22
}

return obj;

public void afterReturning(Object returnValue, Method method,

23
Object[] args, Object target) throws Throwable {

24 25 26 27 28 29 30} 31 32
} }

System.out.println("AfterReturning Advice : Driver locks the car");

public void afterThrowing(Throwable throwable) { System.out.println("AfterThrowing Advice : Accident Encountered");

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

2) Explain Spring? 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. 3) 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 4) 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. 5) 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.

6) 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 Springs metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects. 7) 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 Springs AOP module to provide transaction management services for objects in a Spring application. 8) 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. Springs transaction management supports each of these ORM frameworks as well as JDBC. 9) 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.

You might also like