Skip to main content

Spring Interview Questions

Q) What is IOC (or Dependency Injection)?
A)
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

Q) What are the different types of IOC (dependency injection) ?
A)
There are three types of dependency injection:
–> Constructor Injection : Dependencies are provided as constructor parameters.
–> Setter Injection : Dependencies are assigned through JavaBeans properties (ex: setter methods).
–> Interface Injection : Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection.

Q) What are the benefits of IOC (Dependency Injection)?
A)
Benefits of IOC (Dependency Injection) are as follows:

Minimizes the amount of code in your application. With IOC containers you do not
care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

Q) What is Spring ?
A)
Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.

Q) What are the advantages of Spring framework?
A)
The advantages of Spring are as follows:

–> Spring has layered architecture. Use what you need and leave you don’t need now.
–> Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
–> Dependency Injection and Inversion of Control Simplifies JDBC
–> Open source and no vendor lock-in.

Q) What are features of Spring ?
A)

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

Q) How many modules are there in Spring? What are they?
A)
Spring comprises of seven modules. They are..
The core container:
The core container provides the essential functionality of the Spring framework. 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.
Spring context:
The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
Spring AOP:
The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
Spring DAO:
The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.
Spring ORM:
The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.
Spring Web module:
The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
Spring MVC framework:
The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.

Q) What is Bean Factory ?
A)
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
–>BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
–> BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

Q) What is Application Context?
A)
A bean factory is fine to simple applications, but to take advantage of
the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
–> A means for resolving text messages, including support for internationalization.
–> A generic way to load file resources.
–> Events to beans that are registered as listeners.

Q) What is the difference between Bean Factory and Application Context ? Important Question
A)
On the surface, an application context is same as a bean factory. But application context offers much more..
–> Application contexts provide a means for resolving text messages, including support for i18n of those messages.
–> Application contexts provide a generic way to load file resources, such as images.
–> Application contexts can publish events to beans that are registered as listeners.
–> Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
–> ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
–> MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.

Q) What are the common implementations of the Application Context ?
A)
The three commonly used implementation of ‘Application Context’ are
–> ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application’s classpath by using the code .
–> ApplicationContext context = new ClassPathXmlApplicationContext(”bean.xml”); FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .
–> ApplicationContext context = new FileSystemXmlApplicationContext(”bean.xml”); XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

Q) How is a typical spring implementation look like ?
A)
For a typical Spring Application we need the following files:
–> An interface that defines the functions.
–> An Implementation that contains properties, its setter and getter methods, functions etc.,
–> Spring AOP (Aspect Oriented Programming)
–> A XML file called Spring configuration file.
–> Client program that uses the function.

Q) What is the typical Bean life cycle in Spring Bean Factory Container ?
A)
Bean life cycle in Spring Bean Factory Container is as follows:
–> The spring container finds the bean’s definition from the XML file and instantiates the bean.
–> Using the dependency injection, spring populates all of the properties as specified in the bean definition
–> If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
–> If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
–> If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
–> If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

Q) What do you mean by Bean wiring ?
A)
The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring.

Q) What do you mean by Auto Wiring?
A)
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.
–> no
–> byName
–> byType
–> constructor
–> autodetect

Q) What is AOP module?

A) The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. Using Spring’s metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects.

Q) What is JDBC abstraction and DAO module?

A) Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.

Q) What are object/relational mapping integration module?

A) Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

Q) What is Spring configuration file?

A) 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.

Q) What does a simple spring application contain?

A) 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.

Q) What is XMLBeanFactory?

A) 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");

Q) How do add a bean in spring application?

A) Example:



In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name.

Q) What are singleton beans and how can you create prototype beans?

A) 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.

Ex:

 
singleton=”false”/>

Q) What are the important beans lifecycle methods?

A) 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.

Q) How can you override beans default lifecycle methods?

A) The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods. Find a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.

       
init-method=”fooSetup” destroy=”fooTeardown”/>


Q) What are Inner Beans?

A) 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.

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

A) There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses of org.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.

Q) What is an Aspect?

A) An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP.

Q) What is a Jointpoint?

A) A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

Q) What is an Advice?

A) 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.

Q) What is a Pointcut?

A) 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.

Q) What is an Introduction in AOP?

A) 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.

Q) What is a Target?

A) 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.

Q) What is a Proxy?

A) 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.

Q) What is meant by Weaving?

A) 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.

Q) What are the different points where weaving can be applied?

A)

  • Compile Time
  • Classload Time
  • Runtime

Q) What are the different advice types in spring?

A)

  • 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

Q) What are the different types of AutoProxying?

A)

  • BeanNameAutoProxyCreator
  • DefaultAdvisorAutoProxyCreator
  • Metadata autoproxying

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

A)


DataAccessException - org.springframework.dao.DataAccessException

Q) Compare Spring with Enterprise Java Beans?

Answer:
As J2EE containers, both Spring and EJB offer the deevloper powerful features for developing applications. Comparing the features:
* Transaction management : EJB must use a JTA transaction manager and supports transactions that span remote method calls. Spring supports multiple transaction environment with JTA, Hibernate, JDO, JDBC, etc and does not support distributed transaction.
* Declarative Transaction support : EJB can define transaction in deployment descriptor and can't declaratively define rollback behaviour. Spring can define transaction in Spring confuguration file and can declaratively define rollback behaviour per method and per exception type.
* Persistence : EJB supports programmatic bean-managed persistence and declarative container managed persistence. Spring provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.
* Declarative security : EJB supports declarative security through users and roles and configured in the deployment descriptor. In Spring, no security implementation out of the box. Acegi provides the declarative security framework built on the top of Spring.
* Distributed computing : EJB provides container managed remote method calls. Spring provides proxying for remote calls via RMI, JAX-RPC, and web services.

Q) How can you reference a bean from another bean in Spring?
Answer:
We use the element to set the properties that reference other beans. The subelement of lets us do this:







Q) What is autowiring in the Spring framework? Explain its type?

Answer:
You wire all of your bean's properties explicitly using the element, However you can have Spring wire them automatically by setting the 'autowire' property on each that you want autowired:




There are four types of autowiring:
* byName :- Attempts to find a bean in the container whose name is the same as the name of the property being wired.
* byType :- Attempts to find a single bean in the container whose type matches the type of the property being wired. If no matching bean is found, the property will not be wired.
* constructor :- Tries to match up one or more beans in the container with the parameters of one of the constructors of the bean being wired.
* autodetect :- Attempts to autowire by constructor first and then using byType. Ambiguity is handled the same way as with constructor and byType wiring.

Q) How will you handle the ambiguities of autowiring in Spring?

Answer:
When sutowiring using byType or constructor, it's possible that the container may find two or more beans whose type matches the property's type or the types of the constructor arguments. What will happen if there are ambiguous beans suitable for autowiring?
Spring can't sort out ambiguities and chooses to throw an exception raher than guess which bean you meant to wire in. If you encounter such ambiguities when autowiring, the best solution is not to autowire the bean.

Q) How will you wire a string value to a property whose type is a non-string?


Answer:
Yes. You can wire a string value to a property whose type is a non-string. The java.beans.PropertyEditor interface provides a means to customize how String values are mapped to non-String types. This interface is implemented by java.beans.PropertyEditorSupport that has two methods:
* getAsText() : returns the String representation of a property's value.
* setAsText(String value) : sets a bean property value from the String value passed in.
If you want to map the non-string property to a String value, the setAsText() method is called to perform the conversion.

Q) What are the various custom editors provided by the Spring Framework?

Answer:
The various custom editors provided by the Spring Framework are:
* PropertyEditor
* URLEditor
* ClassEditor
* CustomDateEditor
* FileEditor
* LocaleEditor
* StringArrayPropertyEditor
* StringTrimmerEditor

Q) Explain the Events and listener in Spring framework?

Answer:
All the Events are the subclasses of abstract class org.springframework.context.ApplicationEvent. These are:
* ContextClosedEvent :- Published when the application context is closed.
* ContextRefereshedEvent :- Published when the application context is initialized or refereshed.
* RequestHandledEvent :- Published within a web application context when a request is handled.

If you want a bean to respond to application events, all you need to do is implement the org.springframework.context.ApplicationListener interface. This interface forces your bean to implement the onApplicationEvent() method, which is responsible for reaching to the application event:

public class RefreshListener implements ApplicaitonListener{
public void onApplicationEvent(ApplicationEvent e) {
some code here//
}

You need to register it within the context:



Q) How to integrate your Struts application with Spring?


Answer:
We have two options that are available to integrate Struts application with Spring:
* Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
* Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.

• Delegate Struts Action management to the Spring framework.

Q) What are ORM’s Spring supports ?

Answer:
Spring supports the following ORM’s :
* Hibernate
* iBatis
* JPA (Java Persistence API)
* TopLink
* JDO (Java Data Objects)
* OJB

Q) What is an Advice in Spring framework?

Answer:
An Advice is a Spring bean. 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. An advice instance can be shared across all advised objects, or unique to each advised object. This corresponds to per-class or per-instance advice.
Advice types in Spring:
* Interception around advice
* Before advice
* Throws advice
* After Returning advice
* Introduction advice

Q) What is throws advice in Spring?

Answer:
The ThrowsAdvice lets you definebehaviour should an exception occur. ThrowsAdvice is a marker interface and contains no method but need to be implemented. A class that implements this interface must have at least one method with either of the following two signatures:
* void afterThrowing(Throwable t)
* void afterThrowing(Method m, Object[] o, Object target, Throwable t)

Q) Define the AOP terminology?

Answer:
Many terms used to define the AOP (Aspect Oriented Programming) features and they are part of the AOP language. These terms must be known to understand the AOP:
* Aspect : An aspect is the cross-cutting functionality you are implementing. It is the aspect, or area of your application you are modularizing. The most common example of aspect is logging. Logging is something that is required throughout an application.
* Joinpoint : A joinpoint is a point in the execution of the application where an aspect can be plugged in.
* Advice : Advice is the actual implementation of our aspect. It is advising your application of new behaviour.
* Pointcut : A pointcut defines at what joinpoints advice should be applied.
* Introduction : An introduction allows you to add new methods or attributes to existing classes.
* Target : A target is the class that is being advised.
* Proxy : A proxy is the object created after applying advice to the target object.
* Weawing : Weawing is the process of applying aspects to a target object to create a new proxied object.

Q) Explain the Weaving process in Spring framework?

Answer:
Weaving is the process of applying aspects to a to a target object to create a new proxied object. The aspects are woven into the target object at the specified joinpoints. The weaving can take place at several points in the target class's lifetime:
* Compile time : Aspects are woven in when the target class is compiled. This requires a special compiler.
* Classload time : Aspects are woven at the time of loading of the target class into the JVM. It is done by ClassLoader that enhances that target class's bytecode before the class is introduced into the application.
* Runtime : Sometimes aspects are woven in during the execution of the applicaion.

Q) Name the interfaces that are used to create an Advice in Spring framework?

Answer:
The interfaces that are used to create an Advice are:
* org.aopalliance.intercept.MethodInterceptor
* org.springframework.aop.BeforeAdvice
* org.springframework.aop.AfterReturningAdvice
* org.springframework.aop.ThrowsAdvice

Q) Explian the Before advice?

Answer:
Before the purchasing of our customer, we want to give them a warm greeting. For this, we need to add functionality before the method buySquishee() is executed. To accomplish this, we extend the MethodBeforeAdvice interface:

public interface MethodBeforeAdvice{
void before(Method m, Object[] args, Object target) throws Throwable
}

This interface provides access to the target method, the arguments passed to this method, and the target object of the method invocation.

Q) Explain the After returning advice?

Answer:
We want to make sure that we thank our patrons after they make their purchase. To do this, we implement AfterReturningAdvice:

public interface AfterReturningAdvice{
void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable
}
}

Like MethodBeforeAdvice, this advice gives you access to the method that was called, the arguments that were passed, and the target object.

Q) Explain the Around advice?


Answer:
The MethodInterceptor provides the ability to do both before advice and after advice in one advice object:

public interface MethodInterceptor{
Object invoke(MethodInvocation invocation) throws Throwable;
}

There are two important difference between MethodInterceptor and the both before and after advice. First, the method interceptor implementation controls the target method invocation, and this invocation done by calling MethodInvocation.proceed(). Second, MethodInterceptor gives you control over what object is returned.

Q) Explain the Regular expression pointcuts?

Answer:
The RegexpMethodPointcut lets you leverage the power of regular expressions to define your pointcuts. It uses Perl-style regular expressions to define the pattern that should match your intended methods.
Common regular expression symbol used are (.) matches any single character, (+) Matches the preceding character one or more times, (*) matches the preceding character zero or more, (\) Escapes any regular expression symbol.
For Example:
If we want to match all the setXxx methods, we need to use the pattern .*set.* (the first wildcard will match any preceding class name.

Q) How will you create Introductions in Spring?

Answer:
The Introductions are little different from Spring advice. Advice are woven at different jointpoints surrounding a method invocation. Introductions affect an entire class by adding new methods and attributes to the adviced class.
Introductions allow you to build composite objects dynamically, affording you the same benefits as multiple inheritance.
Introductions are implemented through IntroductionMethodInterceptor, a subinterface of MethodInterceptor. This method adds one method:
boolean implementsInterface(Class intf);
This method returns true if the IntroductionMethodInterceptor is responsible for implementing the given interface.

Q) What is ProxyFactoryBean? Describe its properties?

Answer:
ProxyFactoryBean creates proxied objects. Like other JavaBeans, it has properties that control its behaviour. ProxyFactoryBean properties are:
* target : The target bean of the proxy.
* proxyInterface : A list of interfaces that should be implemented by the proxy.
* interceptorNames : The bean names of the advice to be applied to the target.
* singleton : Whether the factory should return the same instance of the proxy for each getBean invocation.
* aopProxyFactory : The implemetation of the ProxyFactoryBean interface to be used.
* exposeProxy : Whether the target class should have access to the current proxy. This is done by calling AopContext.getCurrentProxy.
* frozen : Whether changes can be made to the proxy's advice once the factory is created.
* optimize : Whether to aggressively optimize generated proxies.
* proxyTargetClass : Whether to proxy the target class, rather than implementing an interface.

Q) What is Autoproxying in Spring?


Answer:
Spring has a facility of autoproxy that enables the container to generate proxies for us. We create autoproxy creator beans. Spring provides two classes to support this:
* BeanNameAutoProxyCreator
* DefaultAdvisorAutoProxyCreator


Q) Explain BeanNameAutoProxyCreator and DefaultAdvisorAutoProxyCreator classes?


Answer:
BeanNameAutoProxyCreator generates proxies for beans that match a set of names. This name matching is similar to the NameMethodMatcherPointcut which allows for wildcard matching on both ends of the name. This is used to apply an aspect or a group of aspects uniformly across a set of beans that follow a similar naming conventions.
The DefaultAdvisorAutoProxyCreator is the more powerful autoproxy creator. Use this class to include it as a bean in your BeanFactory configuration. It implemnts the BeanPostProcessor interface. DefaultAdvisorAutoProxyCreator only works with advisors.

Q) What is Metadata autoproxying?


Answer:
Spring also supprts autoproxying driven by metadata. Metadata autoproxy configuration is determined by source level attributes and keeps AOP metadata with the source code that is being advised. This lets your code and configuration metadata in one place.
The most common use of metadata autoproxying is for declarative transaction support.

Q) Explain DAO in Spring framework?


Answer:
Spring Framework's Data Access Object (DAO) support provides integration of heterogeneous Java Database Connectivity (JDBC) and Object-Relational Mapping (ORM) products. DAO support is provided for JDBC, Hibernate, iBATIS, Java Data Objects (JDO), Java Persistence API (JPA), Oracle's TopLink and Common Client Interface (CCI).

Q) Explain the Spring's DataAccessException?


Answer:
Spring's org.springframework.dao.DataAccessException extends the NestedRuntimeException which in turn extends and RuntimeException. Hence DataAcccessException is a RuntimeException so there is no need to declare it in the method signature.

Q) List the Springs's DAO exception hierarchy?

Answer:
Springs's DAO exception hierarchy is :
* CleanupFailureAccessException
* DataAccessResourceFailureException
* DataIntegrityViolationException
* DataRetrievalFailureException
* DeadlockLoserDataAccessException
* IncorrectUpdateSemanticsDataAccessException
* InvalidDataAccessApiUsageException
* InvalidDataAccessResourceUsageException
* OptimisticLockingFailureException
* TypeMismatchDataAccessException
* UncategorizedDataAccessException

Q) What is JdbcTemplate class used for in Spring's JDBC API?


Answer:
The JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC since it handles the creation and release of resources. This class executes SQL queries, update statements or stored procedure calls, imitating iteration over ResultSets and extraction of returned parameter values. It also catches JDBC exceptions defined in the hierarchy of org.springframework.dao package. Code using the JdbcTemplate only need to implement callback interfaces, giving them a clearly defined contract.
The PreparedStatementCreator callback interface creates a prepared statement given a Connection provided by this class, providing SQL and any necessary parameters. The JdbcTemplate can be used within a DAO implementation via direct instantiation with a DataSource reference, or be configured in a Spring IOC container and given to DAOs as a bean reference.
Example:

A simple DAO class looks like this.
public class StudentDaoJdbc implements StudentDao {
private JdbcTemplate jdbcTemplate;

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


Q) What is NamedParameterJdbcTemplate class used for in Spring's JDBC API?


Answer:
The NamedParameterJdbcTemplate class adds support for programming JDBC statements using named parameters (as opposed to programming JDBC statements using only classic placeholder ('?') arguments. The NamedParameterJdbcTemplate class wraps a JdbcTemplate, and delegates to the wrapped JdbcTemplate to do much of its work.

Q) Name the JDBC Core classes to control basic JDBC processing and error handling in Spring's JDBC API?

Answer:
the JDBC Core classes to control basic JDBC processing and error handling in Spring's JDBC API are :
* JdbcTemplate
* NamedParameterJdbcTemplate
* SimpleJdbcTemplate (Java5)
* DataSource
* SQLExceptionTranslator

Q) what classes are used to Control the database connection in Spring's JDBC API?

Answer:
The classes that are used to Control the database connection in Spring's JDBC API are :
* DataSourceUtils
* SmartDataSource
* AbstractDataSource
* SingleConnectionDataSource
* DriverManagerDataSource
* TransactionAwareDataSourceProxy
* DataSourceTransactionManager


Q) How do you configure your database driver in spring?


Answer:
To configure your database driver using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". For Example:



org.hsqldb.jdbcDriver


jdbc:hsqldb:db/appfuse

sa



Q) How can you configure JNDI instead of datasource in spring applicationcontext.xml?

Answer:
You can configure JNDI instead of datasource in spring applicationcontext.xml using "org.springframework.jndi.JndiObjectFactoryBean". For Example:



java:comp/env/jdbc/appfuse




Q) How can you create a DataSource connection pool?


Answer:
To create a DataSource connection pool :



${db.driver}


${db.url}


${db.username}


${db.password}




Q) Explain about PreparedStatementCreator?

Answer:
The PreparedStatementCreator interface is a 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. 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.
It has one method:
PreparedStatement createPreparedStatement(Connection con) throws SQLException

Create a statement in this connection. Allows implementations to use PreparedStatements. The JdbcTemplate will close the created statement.

Q) Explain about BatchPreparedStatementSetter?


Answer:
BatchPreparedStatementSetter interface sets values on a PreparedStatement provided by the JdbcTemplate class for each of a number of updates in a batch using the same SQL. Implementations are responsible for setting any necessary parameters. SQL with placeholders will already have been supplied. Implementations of BatchPreparedStatementSetter 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.
BatchPreparedStatementSetter has two method:

* int getBatchSize() :- Return the size of the batch.
* void setValues(PreparedStatement ps, int i) :-Set values on the given PreparedStatement.


Q) What are the benefits of the Spring Framework transaction management ?

Answer:
Spring Framework supports:
* Programmatic transaction management.
* Declarative transaction management.

Spring provides a unique transaction management abstraction, which enables a consistent programming model over a variety of underlying transaction technologies, such as JTA or JDBC. Supports declarative transaction management. Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA. Integrates very well with Spring's various data access abstractions.

Q) Advantages of integrating Struts with Spring?

The advantages of integrating a Struts application into the Spring framework are:
1. Spring framework is based on new design approach and was designed to resolve the existing problems of existing Java applications such as performance.
2. Spring framework lets you apply AOP (aspect-oriented programming technique) rather than object-oriented code.

Spring provides more control on struts actions. That
may depend on the method of integration you choose.


Comments

Unknown said…
đồng tâm
game mu
cho thuê nhà trọ
cho thuê phòng trọ
nhac san cuc manh
số điện thoại tư vấn pháp luật miễn phí
văn phòng luật
tổng đài tư vấn pháp luật
dịch vụ thành lập công ty trọn gói
nước cờ trên bàn thương lượng
mbp
erg
nghịch lý
chi square test
nghệ thuật nói chuyện
coase
thuyết kỳ vọng
chiến thắng con quỷ trong bạn
cân bằng nash

- Quốc Đống, anh đừng ở đây mà nói linh tinh. Đây là Ban Tuyên giáo, là cơ quan phát ngôn của Đảng, mấy lời mê tín này sao có thể nói ra.
Hàn Đông cười hì hì, cô ngồi ở đó xem tài liệu và trả lời hắn. Triệu Quốc Đống kiên nhẫn ở lại với cô như vậy làm cô thấy rất hạnh phúc.

- Sao lại nói là mê tín. Văn hóa truyền thống mấy ngàn năm của Trung Quốc có điểm độc đáo mà, không thể vơ đũa cả nắm. Ngay cả chủ tịch Mao cũng không phải chủ trương việc trăm hoa đua nở trong ngành truyền thông sao? Bây giờ không như trước kia, sao có thể vì lời nói mà bị tội?
Triệu Quốc Đống chắp tay sau lưng ra vẻ lãnh đạo nhìn xuống dưới.

- Hừ, anh đừng có ba hoa trước mặt em. Quốc Đống, từ huyện lên tỉnh thì anh phải chú ý cách nói năng của mình, đừng để người ta thấy anh quá xúc động.
Hàn Đông gắt giọng nói.

- xuống, tất cả lời nói đều do thời gian, địa điểm và đối tượng nên có sự thay đổi. Nếu anh ở bên em mà ra vẻ mặt lạnh, nói chuyện xa xa gần gần thì sợ là em sớm đá anh ra ngoài rồi mà?
Triệu Quốc Đống mặt dày cười hì hì nói.

Hàn Đông trừng mắt nhìn hắn đầy tức tối, xem ra cô không thể làm gì được tên vô lại này.

Hắn ở trước mặt cô lúc thì tỏ vẻ như nhà hiền triết, khi thì như một người bề trên, bây giờ lại như một thanh niên tinh nghịch, điều này làm cô thấy mơ mơ hồ hồ. Rất nhiều người ở Thị ủy này muốn làm quen với cô, nhưng cô không thèm để ý. Chẳng lẽ còn chờ đợi trong vô vọng sao?

Hắn hình như biết điều kiện gia đình nhà mình, nhưng lại không hề hỏi, cũng không đi tìm cô mà tạo quan hệ. Duy nhất chỉ có hai lần giúp hắn đều là do quan hệ công việc hoặc là giúp bạn.

Nghe nói hắn bị đưa tới Lĩnh Đông, Hàn Đông còn nghĩ Triệu Quốc Đống sẽ nhờ mình giúp. Nhưng chưa đầy tháng mà người này đã được điều tới Sở Giao thông. Bh như vậy làm Hàn Đông càng lúc càng không hiểu rõ hắn. Mình nên làm như thế nào bây giờ? Cứ chờ đợi như vậy sao?

Popular posts from this blog

Sorting an List in Java

// Create a list String[] strArray = new String[] {"z", "a", "C"}; List list = Arrays.asList(strArray); // Sort Collections.sort(list); // C, a, z // Case-insensitive sort Collections.sort(list, String.CASE_INSENSITIVE_ORDER); // a, C, z // Reverse-order sort Collections.sort(list, Collections.reverseOrder()); // z, a, C // Case-insensitive reverse-order sort Collections.sort(list, String.CASE_INSENSITIVE_ORDER); Collections.reverse(list); // z, C, a

Linked List Example

/* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */ /** * This class implements a linked list that can contain any type of object that * implements the nested Linkable interface. Note that the methods are all * synchronized, so that it can safely be used by multiple threads at the same * time. */ public class LinkedList { /** * This interface defines the methods required by any object that can be * linked into a linked list. */ public interface Linkable { public Linkable getNext(); // Returns the next element in the list public...