Professional Documents
Culture Documents
2
implementation of the factory pattern which removes the need for programmatic singletons and allows
you to decouple the configuration and specification of dependencies from your actual program logic.
BeanFactory create object for you based on XML configuration.
Context package build on the solid base provided by the Core package: it provides a way to access
objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI-registry. The context
package inherits its features from the beans package and adds support for internationalization (I18N)
(using for example resource bundles), event-propagation, resource-loading, and the transparent creation
of contexts.
DAO package provides a JDBC-abstraction layer that removes the need of JDBC coding and parsing of
database-vendor specific error codes. JDBC package provides a way to do programmatic as well as
declarative transaction management, not only for classes implementing special interfaces, but for all your
POJOs (plain old Java objects).
ORM package provides integration layers for popular object-relational mapping APIs, including
JPA,JDO, Hibernate, and iBatis. Using the ORM package you can use all those O/R-mappers in
combination with all the other features Spring offers, such as the simple declarative transaction
management feature mentioned previously.
AOP Aspect-oriented programming, or AOP, is a programming technique that allows
programmers to modularize crosscutting concerns, or behavior that cuts across the typical
divisions of responsibility, such as logging and transaction management. The core construct of
AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable
modules.
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.
MVC package provides a Model-View-Controller (MVC) implementation for web-applications. Spring's
MVC framework is not just any old implementation; it provides a clean separation between domain
model code and web forms, and allows you to use all the other features of the Spring Framework.
6. Benefits of Using Spring Framework
1.
2.
3.
4.
5.
6.
7.
8.
3
2. 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.
3. Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by separating
application business logic from system services.
4. Container:
Spring contains and manages the life cycle and configuration of application objects.
5. MVC Framework:
Spring comes with MVC web application framework, built on core Spring functionality. This
framework is highly configurable via strategy interfaces, and accommodates multiple view
technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used
instead of Spring MVC Framework.
6. Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing
the developer to add the pluggable transaction managers, and making it easy to demarcate
transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE
environments and it can be also used in container less environments.
7. JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which
simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring
provides best Integration services with Hibernate, JDO and iBATIS
8. What are the benefits of IOC?
1. Spring Coremodule
2. Spring Beansmodule
3. Spring Contextmodule
4. Spring Expression Languagemodule
10. What is a BeanFactory?
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate
the applications configuration and dependencies from the actual application code.
ClassPathXmlApplicationContext, FileSystemXmlApplicationContext,
XmlWebApplicationContext, AnnotationConfigWebApplicationContext
17. What do you mean by Bean wiring?
The act of creating associations between application components (beans) within the Spring container is
reffered to as Bean wiring.
8
We can control the bean instantiation process by three ways:
1. Using @PostConstruct annotation
2. Implementing InitializingBean interface with afterPropertiesSet() method
3. Configuring init-method attribute for the bean in the xml configuration file
32. How can we control bean destruction process? How to customize bean destruction process?
We can control the bean destruction process by three ways:
1. Using @PreDestroy annotation
2. Implementing DisposableBean interface with destroy() method
3. Configuring destroy-method attribute for the bean in the xml configuration file
33. What are the JSR-250 Annotations? Explain them.
Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource
annotations.
1. @PostConstruct: This annotation can be used as an alternate of initialization callback.
2. @PreDestroy: This annotation can be used as an alternate of destruction callback.
3. @Resource : This annotation can be used on fields or setter methods. The @Resource annotation
takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it
follows by-name autowiring semantics.
34. What is Spring Java Based Configuration? Give some annotation example.
Java based configuration option enables you to write most of your Spring configuration without XML but
with the help of few Java-based annotations.
For example: Annotation @Configuration indicates that the class can be used by the Spring IoC
container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated
with @Bean will return an object that should be registered as a bean in the Spring application context.
35. How is event handling done in Spring?
Event handling in the ApplicationContext is provided through the ApplicationEvent class and
ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an
ApplicationEvent gets published to the ApplicationContext, that bean is notified.
36. Describe some of the standard Spring events.
Spring provides the following standard events:
1. ContextRefreshedEvent: This event is published when the ApplicationContext is either
initialized or refreshed. This can also be raised using the refresh() method on the
ConfigurableApplicationContext interface.
2. ContextStartedEvent: This event is published when the ApplicationContext is started using the
start() method on the ConfigurableApplicationContext interface. You can poll your database or
you can re/start any stopped application after receiving this event.
3. ContextStoppedEvent: This event is published when the ApplicationContext is stopped using
the stop() method on the ConfigurableApplicationContext interface. You can do required
housekeep work after receiving this event.
9
ContextClosedEvent: This event is published when the ApplicationContext is closed using the
close() method on the ConfigurableApplicationContext interface. A closed context reaches its end
of life; it cannot be refreshed or restarted.
5. RequestHandledEvent: This is a web-specific event telling all beans that an HTTP request has
been serviced.
4.
10
Weaving can be done at compile time, load time, or at runtime.
46. What are the types of advice?
Spring aspects can work with five kinds of advice mentioned below:
1. before: Run advice before the a method execution.
2. after: Run advice after the a method execution regardless of its outcome.
3. after-returning: Run advice after the a method execution only if method completes successfully.
4. after-throwing: Run advice after the a method execution only if method exits by throwing an
exception.
5. around: Run advice before and after the advised method is invoked.
47. What are the different points in the target objects life time where Weaving can be applied?
Weaving can take place at several points in the target objects lifetime:
Compile time: Aspects are woven when the target class is compiled. This requires a special compiler.
AspectJs weaving compiler weaves aspects this way.
Classload time: Aspects are woven when the target class is loaded into the JVM. This requires a
special ClassLoader that enhances that target classs byte code before the class is introduced into the
application. AspectJ 5s load time weaving (LTW) support weaves aspects in this way.
Runtime: Aspects are woven sometime during the execution of the application. Typically, an AOP
container will dynamically generate a proxy object that will delegate to the target object while
weaving in the aspects. Spring AOP uses this approach.
11
Declarative transaction management: This means you separate transaction management from
the business code. You only use annotations or XML based configuration to manage the
transactions.
12
13
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="hibernateProperties" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value=" jdbc:mysql://localhost/hibernate" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
65. How to integrate Spring and Hibernate using HibernateDaoSupport?
Spring and Hibernate can integrate using Springs SessionFactory called LocalSessionFactory. The
integration process is of 3 steps.
Configure the Hibernate SessionFactory
Extend your DAO Implementation from HibernateDaoSupport
Wire in Transaction Support with AOP
66. What are the types of the transaction management Spring supports ?
Spring Framework supports:
Programmatic transaction management.
Declarative transaction management.
67. What are the benefits of the Spring Framework transaction management ?
The Spring Framework provides a consistent abstraction for transaction management that delivers the
following benefits:
Provides a consistent programming model across different transaction APIs such as JTA,
JDBC, Hibernate, JPA, and JDO.
Supports declarative transaction management.
Provides a simpler API for programmatic transaction management than a number of
complex transaction APIs such as JTA.
68. Why most users of the Spring Framework choose declarative transaction management ?
Most users of the Spring Framework choose declarative transaction management
because it is very simple and easy to use. We can wire up a transaction manager in
the Spring configuration file and annotate a class, interface or a public method with
@Transactional and the things are done. The best practice to use @Transactional
annotation for concrete classes only.
69. When to use programmatic and declarative transaction management ?
Programmatic transaction management is usually a good idea only if you have a small number of
transactional operations.
14
On the other hand, if your application has numerous transactional operations, declarative transaction
management is usually worthwhile. It keeps transaction management out of business logic, and is not
difficult to configure.
70. Explain the similarities and differences between EJB CMT and the Spring Framework's
declarative transaction management ?
The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to
individual method level. It is possible to make a setRollbackOnly() call within a transaction context if
necessary. The differences are:
Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction
management works in any environment. It can work with JDBC, JDO, Hibernate or other
transactions under the covers, with configuration changes only.
The Spring Framework enables declarative transaction management to be applied to any class,
not merely special classes such as EJBs.
The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent.
Both programmatic and declarative support for rollback rules is provided.
The Spring Framework gives you an opportunity to customize transactional behavior, using AOP.
With EJB CMT, you have no way to influence the container's transaction management other than
setRollbackOnly().
The Spring Framework does not support propagation of transaction contexts across remote calls,
as do high-end application servers.
71. Explain about the Spring DAO support ?
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access
technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the
persistence technologies fairly easily and it also allows one to code without worrying about catching
exceptions that are specific to each technology.
72. What are the exceptions thrown by the Spring DAO classes ?
Spring
DAO
classes
throw
exceptions
which
are
subclasses
of
DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient
translation from technology-specific exceptions like SQLException to its own exception class hierarchy
with the DataAccessException as the root exception. These exceptions wrap the original exception.
73. What is SQLExceptionTranslator ?
SQLExceptionTranslator is a strategy interface for translating SQLExceptions into Springs
DataAccessException hierarchy. Implementations can be generic (for example, using SQLState codes for
JDBC) or wholly proprietary (for example, using Oracle error codes) for greater precision.
74. What is Spring's JdbcTemplate ?
The JdbcTemplate class is the central class in the JDBC core package. It handles the creation and release
of resources, which helps you avoid common errors such as forgetting to close the connection. It performs
the basic tasks of the core JDBC workflow such as statement creation and execution, leaving application
code to provide SQL and extract results. The JdbcTemplate class executes SQL queries, update statements
15
and stored procedure calls, performs iteration over ResultSets and extraction of returned parameter
values. It also catches JDBC exceptions and translates them to the generic, more informative, exception
hierarchy defined in the org.springframework.dao package.
JdbcTemplate template = new JdbcTemplate(myDataSource);
75. How JdbcTemplate can be used? How do you write data to backend in Spring using JdbcTemplate?
<!-- EmployeeDAO -->
<bean id="employeeDAO" class="jdbc.EmployeeDAO">
<property name="template" ref="jdbcTemplate"></property>
</bean>
<!-- JDBCTemplate -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="mySQLDS"></property>
</bean>
<!-- DriverManagerDataSource -->
<bean id="mySQLDS"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
76. What is SQLProvider?
SqlProvider is an interface that needs to be implemented by objects that can provide SQL strings.
Typically
implemented
by
PreparedStatementCreators,
CallableStatementCreators
and
StatementCallbacks that want to expose the SQL they use to create their statements, to allow for better
contextual information in case of exceptions.
77. What is PreparedStatementCreator?
The PreparedStatementCreator callback interface creates a prepared statement given a Connection
provided by this class, providing SQL and any necessary parameters. PreparedStatementCreator is one of
the two central callback interfaces used by the JdbcTemplate class. This interface creates a
PreparedStatement given a connection provided by the JdbcTemplate class. Implementations are
responsible for providing SQL and any necessary parameters. Implementations do not need to concern
themselves with SQLExceptions that may be thrown from operations they attempt. The JdbcTemplate
class will catch and handle SQLExceptions appropriately. A PreparedStatementCreator should also
implement the SqlProvider interface if it is able to provide the SQL it uses for PreparedStatement
creation. This allows for better contextual information in case of exceptions.
16
EJB
Spring
Transaction
management
Supports
multiple
transaction
environments
through
its
Must use a JTA transaction
PlatformTransactionManager interface, including
manager.
JTA, Hibernate, JDO, and JDBC.
Supports transactions that
Does not natively support distributed
span remote method calls.
transactionsit must be used with a JTA
transaction manager.
17
Declarative
transaction
support
Can
define
transactions
Can define transactions declaratively
declaratively through the deployment
through the Spring configuration file or through
descriptor.
class metadata.
Can
define
transaction
Can define which methods to apply
behavior per method or per class by
transaction behavior explicitly or by using regular
using the wildcard character *.
expressions.
Cannot declaratively define
Can declaratively define rollback
rollback behaviorthis must be done
behavior per method and per exception type.
programmatically.
Persistence
Supports
programmatic
bean- Provides a framework for integrating with several
managed persistence and declarative persistence technologies, including JDBC,
container managed persistence.
Hibernate, JDO, and iBATIS.
Declarative
security
Distributed
computing
Provides container-managed remote Provides proxying for remote calls via RMI, JAXmethod calls.
RPC, and web services.
18
19
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new EmployeeValidator());
}
}
87. Can any object be used as command while using Spring Web MVC Framework?
In Spring Web MVC you can use any object as a command or form-backing object; you do not need to
implement a framework-specific interface or base class. Springs data binding is highly flexible: for
example, it treats type mismatches as validation errors that can be evaluated by the application, not as
system errors. Thus you need not duplicate your business objects properties as simple, untyped strings in
your form objects simply to handle invalid submissions, or to convert the Strings properly. Instead, it is
often preferable to bind directly to your business objects.
88. What is ModelAndView?
ModelAndView is a holder for both Model and View in the web MVC framework. Model and View are
entirely distinct. This class merely holds both to make it possible for a controller to return both Model and
View in a single return value. It represents a Model and View returned by a handler, to be resolved by a
DispatcherServlet. The View can take the form of a String view name which will need to be resolved by a
ViewResolver object; alternatively a View object can be specified directly. The model is a Map, allowing
the use of multiple objects keyed by name.
89. What is Spring Security?
Spring Security module provides authentication, authorization and other security features for enterprise
applications.
90. Difference between FileSystemResource and ClassPathResource?
FileSystemResource will look into the file system and ClassPathResource will look into the class
path for the Spring configuration file.
FileSystemResource uses path relative to the project but ClassPathResource uses path relative to
the class path. For example:
91. How can we control concurrent active session using Spring Security?
We need to add HttpSessionEventPublisher in web.xml file:
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
We need to add the following lines in application context:
20
<http>
...
<session-management>
<concurrency-control max-sessions="1" />
</session-management>
</http>
or
21
<value>file:E:\MyRnD\java\hello.properties</value>
</list>
</property>
</bean>
95. How to go about reading environment specific property files?
We can use PropertyPlaceholderConfigurer or PropertySourcesPlaceholderConfigurer which will enable
other beans to access properties from environment specific properties file via ${. . .} notation.
<bean id="hello"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:E:\MyRnD\java\hello.properties</value>
</list>
</property>
</bean>
Alternatively we can use the smaller syntax with <property-placeholder> element:
<context:property-placeholder location="file:E:\MyRnD\java\b.properties" />
96. How to inject a java.util.Properties into abean?
We can inject a java.util.Properties into a bean using PropertiesFactoryBean.
MyBean.java
package com;
import java.util.Properties;
public class MyBean {
private Properties map;
public Properties getMap() {
return map;
}
public void setMap(Properties map) {
this.map = map;
}
}
beans.xml
<bean id="myBean" class="com.MyBean">
<property name="map" ref="hello" />
</bean>
<bean id="hello"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:com/a.properties</value>
</list>
</property>
22
</bean>
97. How can you create a DataSource connection pool?
<bean
id="springDataSource"
class="org.apache.commons.dbcp.BasicDataSource"
method="close" >
<property name="url" value="jdbc:oracle:thin:@localhost:1521:test" />
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="removeAbandoned" value="true"/>
<property name="initialSize" value="20" />
<property name="maxActive" value="30" />
</bean>
98. Which Design Patterns are used in Spring?
The list of Design Patterns is used in Spring is huge:
1. Creational patterns:
a. Singleton Pattern: Default bean scope
b. Factory Method Pattern: BeanFactory
c. Prototype Pattern: Bean scope
2. Structural patterns:
a. Adapter Pattern: Spring Web, Spring AOP
b. Proxy Pattern: Spring AOP
3. Behavioral patterns:
a. Command Pattern: Spring MVC
b. Observer Pattern: Events
c. Strategy Pattern: SQLExceptionTranslator
d. Template Method Pattern: JdbcTemplate, HibernateTemplate
4. Presentation Tier Design Patterns:
a. Front Controller
b. Application Controller
c. Page Controller
d. Context Object
e. Intercepting Filter
f. View Helper
g. Composite View
h. Dispatcher View
i. Service to Worker
5. Business Tier Design Patterns:
a. Service Locator
b. Business Delegate
c. Session Facade
d. Application Service
e. Business Interface
destroy-
23
6. Integration Tier Design Patterns:
a. Data Access Object
b. Procedure Access Object
c. Service Activator
d. Web Service Broker
7. Crosscutting Design Patterns:
a. Authentication and Authorization Enforcer
b. Audit Interceptor
c. Domain Service Owner Transaction