Showing posts with label Beginner. Show all posts
Showing posts with label Beginner. Show all posts

Spring MVC Framework Spring Interview Questions - 1

Spring is one of the most widely used framework in the Java/J2EE application. Almost all the job postings / consultancy requirements list Spring as one of the key skills. So it is no surprise that most of the interviews contains a wide list of Spring related questions. Here we will try to list some of the basic questions asked on the Spring Framework.
Question 1: What is Spring Framework?
Spring is an open source lightweight inversion of control application framework that supports the various aspects of application development.

Question 2: What are its features?
Spring has the following features:
  • Lightweight
  • Inversion of Control - A component lists its dependencies rather than looking for dependent objects.
  • Container - Contains and manages the lifecycle of various application components.
  • Aspect Oriented - Cross cutting concerns are handled separately through AOP module.
  • Transaction Management - Spring container provides an abstract layer of components to handle the transaction management thus allowing the developers to concentrate more on the business logic and allowing them to demarcate the transactions without worrying about the low-level issues, by providing plugable transaction managers. The spring transaction management can be run in a container less environment as well.  
  • JDBC Handling - Spring can be easily integrated with the Hibernate, JDO and iBATIS.
  • MVC Framework - Spring comes with a MVC framework as well which can use various presentation technologies like JSP, JSF, Velocity and Tiles etc. However, if you wish you to use some other MVC framework spring can be easily integrated with them as well.
Question 3: What is Inversion of Control / IoC?
Inversion of Control or IoC is a phenomenon used by frameworks to invert the control. Basically, in traditional programming the user / developer control the calling of a procedure, however when using IoC the framework controls the calling mechanism. Hence, saying simply that the framework calls us, we don't call it. Although the above statement state the calling of procedure, this can be used for any development term like instantiation etc. A better and elaborated discussion can be found here by Martin Fowler. Servlets, EJB, template method pattern can be stated as examples of Inversion of Control, in general they are Inverting the control. (Hint: Don't call us, we will call you.)

Question 4: How is Inversion of Control different from Dependency Injection?
Inversion of Control is a principle that is being followed in many frameworks, however dependency injection in one such patter that is built on top of IoC. IoC is generally followed in all framework as they are trying to invert some sort of control, however every framework may not provide you with dependency injection. In dependency injection it is the dependency creation control that is being inverted. In DI, rather than object creating the dependencies the framework will invert the control and inject dependencies. More on this can be found here.

Question 5: What pattern does Spring uses to create beans?
Generally there are lot of design patterns used in Spring to create beans. For Example,
  • Proxy interface, in case of AOP
  • Singleton, beans created in spring are singleton by default
  • Template method, in case of JdbcTemplate, JmsTemplate etc.
  • Abstract Factory pattern, is use to register and then instantiate various beans defined in the Configuration file.
Question 6: What are the ways to inject beans in Spring and which one should be used where?
In Spring beans can be inject by the setter method or by constructor. In Setter Injection, the bean is created using the default constructor or no-arg constructor and then the setter methods are called in to inject various beans. In Constructor Injection, the bean is created using the Constructed with a number of arguments and then these arguments can be inject while instantiation. Now the question arises which one should be used. IMHO I think we should use a combination of both. You should have a constructor with the "Required" arguments or collaborators and should have setter injection for dependencies which are optional. In this way, you are also making sure that you have all the required dependencies during its instantiation and optional properties can be set using setter injection. You can refer to the following blog at springsource to learn more about the above reason.

Question 7: What is JdbcTemplate in Spring DAO?
JDBCTemplate is the central class in the Spring DAO module, it has the template methods to open and close various resources, hence decreasing the programming errors. This class provides the basic workflow for a JDBC like opening the connection, preparing the statement , executing and then closing the connection thus leaving the application code to only provide the SQL and retrieve the results. It has methods for executing SQL queries, update statements and procedure calls. It also provides the methods for iterating over a result set. This class also catches SQL Exceptions and generates more informative exceptions defined in the Spring Exception hierarchy.



Spring MVC Framework Collection API Questions - 1

Java Collection Framework is one of the hot favourite among interviewers. The reason for that is any Java program uses Java Collection Framework intensively and any manager hiring for his team would like to see that you have basic and some advanced knowledge in the Collection API. Other reason that I find for interest in Collection Framework is that the questions will help in identifying whether the candidate knows how the various Data Structures are implemented in Java explaining his interest. 

In this post I will try to list some of the beginner to advanced level questions asked on the Collection Framework.


Question 1: What is the Java's collection API?
Java's Collection API is a unified architecture of interfaces, classes and algorithms that are required for representing and manipulation of Collections. For example, List, Map, Set and the like. Benefit of these classes is as follows:
1.        It reduces the programming effort for the developers.
2.        It increases the program speed and quality, since the Collection API provides the high-performance and high quality implementation of the data structure and the algorithms required for their manipulation.
2.        It increase software re-usability.
3.        Reduces efforts to learn and create basic data structures API’s

An excerpt from the Java's Collection Trail 



















Question 2: What are the basic interfaces in the Collection API?
Basic interfaces in the collection API are:

1. Collection: This is the parent interface and all other interfaces extend this interface.
2. Set: This is a core interface to represent a mathematical set, the basic thing about a set is it 
             does not have duplicate values and at most have one null value.
3. List: An ordered collection or sequence, the user of this interface has precise control over 
            where each element is inserted. The user can access each element by its index /  
            position. It differs from the set in the way, that it allows duplicates and null values.
4. Queue: This is a collection used to hold multiple elements prior to processing. Queues 
                  typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. 
                 Among the exceptions are priority queues, which order elements according to a  
                 supplied comparator or the elements' natural ordering. Whatever the ordering used, 
                 the head of the queue is the element that would be removed by a call to remove or  
                 poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other 
                 kinds of queues may use different placement rules.
5. Map: This is a collection of key-value pair. A Map cannot contain duplicate keys; each key 
              can map to at most one value.

The other two core interfaces are merely sorted versions of set and map.

1. SortedSet: This is a Set that maintains its elements in ascending order. Several additional  
                        operations are provided to take advantage of the ordering.
2. SortedMap: This is a Map that maintains its mappings in ascending key order.

Their hierarchy is depicted in the below diagram.


Question 3: What is the difference between Set and List?
The basic difference between a Set and List is that set does not allow duplicates and allows at most one null value. Also, List is an ordered collection of elements whereas set is an unordered collection of elements.

Question 4: Why doesn't Map interface extend Collection?
Theoretically, let us assume that Map extends Collection, So what exactly are the elements of this collection? The only answer to this is "key-value" pair. But you cannot really iterate over these elements without knowing the value of key. However, Map can be viewed as a collection of the keys, values, key-value pair or entrySets. Depicting this behaviour Map does provide the collection view method keySets(), values(), entrySets().

Similary, if the Collection interface extends Map interface, then what are the keys of these elements. There is no satisfactory example.While it is possible to view List as a possible map with the indices as the keys, this has a property that when you remove an element from the List, it changes the keys of the elements preceding it and hence the reason that we don't have Map view operations on the list.

Question 5: Why doesn't Collection extends Cloneable or Serializable interface?
The only answer I can think of is that it is rarely required to clone or serialize the whole collection. There are serializable / cloneable implementations of the Collection. So, if the user want to create a Cloneable/Serializable collection, he can create a generic collection and then can use addAll() to insert the collection in a cloneable / serializable collection implementation.

Question 6: What are the other useful interfaces in Collection Framework?
Other useful interfaces are:

  • Iteration : Enumerator, Iterator, ListIterator
  • Ordering: Comparable, Comparator
  • Performance: RandomAccess
Question 7: What is the difference between Enumerator, Iterator and ListIterator?
Property
Enumeration
Iterator
ListIterator
Number of method
2
3
9
Method names
hasMoreElements(), nextElement()
hasNext(), next(), remove().
add(), hasNext(), next(), hasPrevious(), previous(), nextIndex(), previousIndex(), set(),remove().
Access Direction
Forward-only
Forward only
Bi-directional
Summary
It provides a read only traversal of the collection. Legacy classes such as Vector and HashTable returns this
Iterator provides a method to remove an element from the iterator. Java Collection Framework classes return this.
It provides a bi-directional access on the collection and hence has methods to support it, like previous() and next(). It also allows the modification of elements using set() and add() operation.


Spring MVC Framework Spring Interview Question - 2

This is the second set of questions that are generally asked during the interviews on Spring Framework. Some of these are advanced level questions like on the MVC architecture.

Question 1: What is BeanFactory?
Bean Factory is a factory class that contains the definition of multiple beans in itself, it can instantiate various beans when asked by the client. It has the capabilities to perform two major task during this process.
  • It is able to resolve the association between collaborating objects as the beans are instantiated. It in term removes the burden of the the configuration from the bean itself or from the calling client.
  • It can also call the various life cycle methods of beans and can calls the instantiation and destruction methods.
Question 2: What is ApplicationContext?
ApplicationContext is also like BeanFactory, the difference being that BeanFactory can only be created programmatically  whereas ApplciationContext can be created declaratively using ContextLoaders, for example a ContextLoaderListener. Apart from being able to perform the lifecycle control just like BeanFactory it can also load the various text message resources, file resources and can also pass the various events to beans that are registered as Listeners.

Question 3: What is Dependency Injection and Why is it becoming the de-facto standards for applications?
Dependency injection is the mechanism provided by framework where in the framework is responsible for creating the various dependencies and injecting them rather than the object creating the dependency. It becoming quite popular these days for the simple reason that it provides a loose coupling between various components. So, tomorrow if one of the dependency  changes rather then the whole application getting effect all the programmers need to do is just change the configuration as long as the changed bean also follows the same "contract" / interface as the previous one.

Question 4: What is the Spring's MVC architecture? or How does a web Request flows through Spring MVC?
Spring MVC architecture consists of the following things:
  • DispatcherServlet
  • LocaleResolver
  • MultipartResolver
  • ThemeResolver
  • HandlerMappings
  • Controller
  • ResultToViewNameTranslator
  • ViewResolver
The above components works as following to serve the request.
  • The DispatcherServlet receives the request from client
  • It uses the LocaleResolver to load any properties based on the Locale of the generated request.
  • It then uses the ThemeResolver to find any specific theme / template that might be used for that particular locale.
  • Then it find out whether the request has a multipart mime type then it initialises the file upload classes.
  • Then it uses the HandlerMappings to find the correct controller, where it uses the Model / Service Layer to execute the business logic. Before calling the controller method it has the capability to call the Pre adn Post Controller interceptor, which largely work as filters. 
  • Then it calls the ResultToViewNameTranslator to find the correct view.
  • Then the controller populates the Model and uses the ViewResolver to find the next view. It then combines the Model and the View to prepare the view, which is then passed to the container to return as Response.
Question 5: What are the main class in the Spring MVC architecture?
The main classes in the MVC architecture are as follows:
  1. DispatcherServlet
  2. MultipartResolver
  3. LocaleResolver
  4. ThemeResolver
  5. HandlerMapping
  6. HandlerAdapters
  7. HandlerExceptionResolver
  8. ResultToViewNameTranslator
  9. ViewResolver
Question 6: What is the typical lifecycle of a bean in the bean factory container?
Bean lifecycle in a bean container is as follows:
  • BeacFactory reads the bean definition from the xml configuration file.
  • BeanFactory instantiate the bean.
  • Using the dependency injection bean factory populates all the bean properties as specified in the bean definition.
  • If the bean implements BeanNameAware interface, then it calls the setBeanName() method passing the bean id.
  • If the bean implements BeanFactoryAware interface, then it calls the setBeanFactory() method passing an instance of itself.
  • If the bean has any BeanPostProcessors associated with itself it will call the postProcessBeforeTheInitialization() method.
  • If any init method is declare it will call that method and initialize the bean.
  • Finally if any BeanPostProcessor is associated with the bean then it will call the postProcessAfterInitialization().
Question 7: What are various Bean scopes available in Spring?
Spring supports the following scopes:
  • singleton - This is the default scope of a spring bean, it means the same instance is available through out the application
  • prototype - This means that the bean act as a template and a new instance will be injected for different beans.
  • request - The bean definition is available till the scope of an HTTP request. This is only applicable in case of the web-aware application context.
  • session - The bean is available till the scope of HTTP session. This is only applicable in case of the web-aware application context.
  • global-session - The bean is available till the scope of a global HTTP session. This is typically applicable in case of portlet context.
Question 8: Why is Spring MVC better than Struts ?