<<

Spring Interview Questions

By Srinivas

Short description:

● Spring Interview Questions for the Developers.

@2016 Attune World Wide All right reserved. www.attuneww.com

Contents

Contents 1. Preface 1.1. About This Guide 1.2. Intended Audience 1.3. Revision History 2. Spring Interview Questions

Spring Interview Questions Last Updated: November 2016 | Page 2 of 19

1. Preface

1.1. About This Guide

In this guide, the readers and the developers of the will find the technical questions and their related answers for their future interviews.

1.2. Intended Audience

This document is helpful for the people who are looking for interview questions in Spring framework.

1.3. Revision History

This document is the first document in this series Spring interview questions.

Spring Interview Questions Last Updated: November 2016 | Page 3 of 19

2. Spring Interview Questions

Q.1 What is Spring Framework? Which are its main modules?

Ans: The Spring Framework is a Java platform which is providing extensive infrastructure support, where we can develop Java applications. With Spring, infrastructure part is handled so we can focus on application part. Presently, in Spring Framework, we have features which have been organized into 20 modules. These modules have been grouped into Data Access/Integration, Core Container, AOP (Aspect Oriented Programming), Web, Messaging, Instrumentation, and Test, in below diagram can be seen.

Spring Interview Questions Last Updated: November 2016 | Page 4 of 19

Q. 2 What are advantages of using Spring Framework?

Following are the list of benefits of using Spring Framework – Lightweight: Spring is very lightweight, and when we are considering transparency and size. The basic version of spring framework is very less.

Aspect oriented (AOP): Spring also supports Aspect oriented programming and gives us the ability for cohesive development, with the separation of application business logic from the system services. Container: Spring manages and contains the lifecycle and configuration of the application objects.

MVC Framework: Spring's MVC framework is a very well-designed , which can provide us a great alternative for web frameworks such as Struts.

Inversion of control (IOC): With Spring, we achieve Loose coupling, in spring with the technique of Inversion of Control. The objects give their dependencies instead of looking or creating for the dependent objects.

Transaction Management: Spring provides us with consistent transaction management which can scale down to a local transaction (using a single database) and scale up to global transactions (using JTA).

Exception Handling: Spring provides us a convenient API for translating technology- specific exceptions (thrown by Hibernate, JDBC, or JDO, for example) into consistent, unchecked exceptions.

Spring Interview Questions Last Updated: November 2016 | Page 5 of 19

Q.3 What are the different modules in Spring framework? Following are the modules of the Spring framework: ● Context module ● Bean module ● Core module ● JDBC module ● ORM module ● Expression Language module ● OXM module ● Transaction module ● Web module ● Web-Servlet module ● Web-Portlet module ● Java Messaging Service(JMS) module ● Web-Struts module Q.4. What is Spring configuration file?

Spring configuration file is a XML file. This file is having the classes information and it also describes how these classes can be introduced and configured to each other.

Q.5 What is ?

Inversion of Control (IoC) can be said as a very common concept, and it can also be expressed in so many different ways and Dependency Injection can be said as one of the concrete example of Inversion of Control.

This concept says, that if we do not create our objects but just describe them, how they have to be created. And also, we don't directly have to connect components and services together in code, but just have to describe which services have to be needed by which components, in configuration file. A container (normally some IOC container) then takes care of hooking it all up.

Spring Interview Questions Last Updated: November 2016 | Page 6 of 19

Q.6 Which DI would you suggest setter-based DI or Constructor-based?

Since we have the chance of mixing both, Setter-based DI and Constructor-based DI, it is a good rule of thumb for using constructor arguments for the mandatory dependencies and setters can be used for the optional dependencies.

See that, the use of a @Required annotation on any setter has to happen for making the setters required dependencies.

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

Types of IoC are: ● Setter-based dependency injection: Setter-based DI can be accomplished by container, and that happens when we are calling setter methods on the beans, after we are invoking a no-argument static factory method or no-argument constructor for instantiating the bean. ● Constructor-based dependency injection: Constructor-based DI can be accomplished, when any container is invoking a class constructor with a number of arguments, each is representing a dependency on the other classes.

Q.8 What is AOP?

AOP or Aspect-oriented programming, is a programming technique that allows programmers in modularizing the behavior or crosscutting concerns, that can cut across typical divisions of responsibility, such as transaction management and logging.

The core construct of AOP is an aspect, which is capable of encapsulating the behaviors which are affecting the multiple classes into the reusable modules.

Spring Interview Questions Last Updated: November 2016 | Page 7 of 19

Q.9 What are the benefits of IOC?

The main advantages of dependency injection or IOC are: ● This makes our application easy for testing, as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases. ● In our application, amount of code gets minimized. ● IOC containers can support the and eager instantiation of services. ● Loose coupling can be promoted with least intrusive mechanism and minimal effort.

Q.10 What are types of IoC containers? Explain them. There are two types of IoC containers: ● Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability for resolving textual messages from a properties file and ability for publishing application events to the interested event listeners. ● Bean Factory container: This can be said as simplest container which has been providing the basic support for DI. The BeanFactory can be normally preferred, where resources are limited like applet based or mobile devices applications.

Q.11 What is Spring IoC container?

The Spring IoC can wire them together, create the objects, configure them, and can also manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.

Q.12 Give an example of BeanFactory implementation.

XmlBeanFactory class can be said as the most commonly used BeanFactory implementation. This container is capable of reading configuration metadata from an XML file and can use it for creating a application or fully configured system.

Spring Interview Questions Last Updated: November 2016 | Page 8 of 19

Q.13 What are the common implementations of the ApplicationContext?

The three commonly used implementation of 'Application Context' are: ● ClassPathXmlApplicationContext: This container is capable of loading the definitions of the beans from XML . Here, we do not need to provide the full path of the XML file but we need for setting the CLASSPATH properly because this container can look for XML bean configuration file in the CLASSPATH. ● FileSystemXmlApplicationContext: This container is capable of loading the definitions of beans from an XML file. Here, we have to provide full path of XML bean configuration file to the constructor. ● WebXmlApplicationContext: This container can load with the XML file, with the definitions of all beans from within some web application.

Q.14 What is the difference between ApplicationContext and Bean Factory?

Following are some of the differences: ● Application contexts can provide us with some means for resolving text messages, including the support for i18n of those messages. ● Application contexts can give us a generic way for loading file resources and with images. ● Application contexts are capable of publishing events to beans that have been 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. ● The application context is also capable of implementing MessageSource, an interface which can be used for obtaining localized messages, with actual implementation being pluggable.

Spring Interview Questions Last Updated: November 2016 | Page 9 of 19

Q.15 What are Spring beans?

The objects which are forming the backbone of application and can also be managed by Spring IoC container are called beans. A bean is an object which has been assembled,instantiated and can otherwise be managed by some Spring IoC container.

These beans can be created with configuration metadata which have to be supplied for the container, for example, in the form of XML definitions.

Q.16 What does a bean definition contain?

The bean definition is having the information which can be called as configuration metadata, and it is much needed for container to know the below things: ● Bean's lifecycle details ● Creating a bean ● Bean's dependencies

Q.17 How can you the provide configuration metadata to the Spring Container? There are following three important methods for providing configuration metadata for the Spring Container: ● XML based configuration file. ● Annotation-based configuration. ● Java-based configuration.

Spring Interview Questions Last Updated: November 2016 | Page 10 of 19

Q.18 How can we add a bean in spring application?

Check the following example:

Q.19 How do you define a bean scope?

When we are defining a in Spring, we have an option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, we should be able to declare the bean's scope attribute to be prototype.

Similarly, if we want Spring to return same bean instance every time one is needed, we should be declaring the bean's scope attribute to be singleton.

Q.20 What bean scopes does Spring support? Explain them.

The Spring Framework can support the following five scopes, three of which are available only if we are using a web-aware ApplicationContext.

Spring Interview Questions Last Updated: November 2016 | Page 11 of 19

● prototype: This scopes a single bean definition for having any number of object instances. ● singleton: This scopes the bean definition to a single instance per Spring IoC container. ● session: This scopes a bean definition to an HTTP session. This is only valid in the context of a web-aware Spring ApplicationContext. ● request: This scopes a bean definition to an HTTP request. This is only valid in the context of a web-aware Spring ApplicationContext. ● global-session: This scopes a bean definition to a global HTTP session. This is only valid in context of a web-aware Spring ApplicationContext.

Q.21 What is default scope of bean in Spring framework? For Spring framework, the default scope of bean is Singleton scope.

Q.22 Are Singleton beans thread safe in Spring Framework? No, singleton beans cannot be considered as thread-safe in Spring framework.

Q.23 Explain Bean lifecycle in Spring framework?

Following is sequence of a bean lifecycle in Spring: Instantiate - Firstly, the spring container finds the bean's definition from XML file and then instantiates bean. Populate properties - Using dependency injection, spring now populates all of the properties which are specified in bean definition.. Set Bean Name - If the bean is implementing the BeanNameAware interface, spring then passes bean's id to setBeanName() method. Set Bean factory - If Bean is implementing BeanFactoryAware interface, spring then passes the beanfactory to setBeanFactory() method. Pre Initialization - Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.

Spring Interview Questions Last Updated: November 2016 | Page 12 of 19

Initialize beans - If the bean is implementing the IntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called then. Post Initialization - If there are any BeanPostProcessors which are associated with bean, their postProcessAfterInitialization() methods will then be called. Ready to use - Now the bean is ready, and can be used by the application. Destroy - If the bean is implementing the DisposableBean , it will call destroy() method.

Q.24 What are inner beans in Spring?

A element is inside the or elements defines a so-called inner bean. An inner bean definition does not require a defined id or name; the container can ignore these values. It can also ignores the scope flag. Inner beans can always be anonymous and they can always be scoped as prototypes.

Q.25 How can you inject Java Collection in Spring? With Spring, we can inject four types of collection configuration elements which are as follows: ● : This helps in wiring a set of values but that too without any duplicates. ● : This can be used to inject a collection of name-value pairs where the name and value are both Strings. ● : This helps in wiring i.e. injecting a list of values, and it may allow duplicates. ● : This can be used to inject a collection of name-value pairs where name and value can be of any type. Q.26 What is bean auto wiring?

The Spring container will be able to autowire the relationships between the collaborating beans. What this means is, it is automatically and possible lets the Spring resolve collaborators (other beans) for your bean with the inspection of contents of BeanFactory, without the usage of and elements.

Spring Interview Questions Last Updated: November 2016 | Page 13 of 19

Q.27 What are different Modes of auto wiring?

The autowiring functionality is having five modes which can be used for instructing the Spring container, to use autowiring for dependency injection: ● no: This can be said as default setting, which means there is no autowiring and we should be using explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter. ● byName: Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. ● autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType. ● Constructor: Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. ● byType: Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.

Q.28 What are the limitations with autowiring? Limitations of autowiring are: ● Primitive data types: You cannot autowire so-called simple properties such as primitives, Strings, and Classes. ● Overriding possibility: You can still specify dependencies using and settings which will always override autowiring. ● Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

Spring Interview Questions Last Updated: November 2016 | Page 14 of 19

Q.29 What does @Qualifier annotation mean? There can be a situation when we can create a more than one bean of same type and want to wire only one of them with a property, in such a case we can use @Qualifier annotation along with @Autowired for removing confusion by specifying which exact bean will be wired.

Q.30 What does @Autowired annotation mean? This annotation gives us more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire a bean on setter method, just like constructor,@Required annotation, a property or methods with arbitrary names and/or multiple arguments.

Q.31 What does @Required annotation mean? This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated. Q.32 How do you turn on annotation wiring? Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring .

Q.33 Can you inject null and empty string values in Spring? Yes.

Q.34 How JdbcTemplate can be used? 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 provides many convenience methods for doing things such as executing prepared and callable statements, converting database data into primitives or objects and providing custom database error handling.

Spring Interview Questions Last Updated: November 2016 | Page 15 of 19

Q.35 What are the types of the transaction management Spring supports? Spring supports two types of transaction management: ● Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain. ● Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration for managing the transactions.

Q.36 Which of the above transaction management type is preferable? Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

Q.37 What is Spring MVC framework? The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.

Q.38 What is a DispatcherServlet? The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.

Q.39 What is WebApplicationContext ? The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with.

Spring Interview Questions Last Updated: November 2016 | Page 16 of 19

Q.40 What is Controller in Spring MVC framework? Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

Q.41 Explain the @Controller annotation. The @Controller annotation can indicate that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.

Q.42 Explain @RequestMapping annotation. @RequestMapping annotation can be used for mapping a URL to either an entire class or some particular handler method.

Q.43 What is a Spring Bean? 1. Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean instance. 2. Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.

Q.44 What are the ways to access Hibernate by using Spring? There are two ways to access hibernate using spring: ● Extending HibernateDAOSupport and Applying an AOP Interceptor node. ● Inversion of Control with a Hibernate Template and Callback.

Q.45 What are ORM's Spring supports ? Spring supports the following ORM's : ● Hibernate ● iBatis ● TopLink

Spring Interview Questions Last Updated: November 2016 | Page 17 of 19

● JDO (Java Data Objects) ● JPA (Java Persistence API) ● OJB

Q.46 What is Aspect? A module which has a set of providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can be having any number of aspects, depending on the requirement. In Spring AOP, aspects are implemented by using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).

Q.47 What is the difference between concern and cross-cutting concern in Spring AOP? Cross-cutting concern: It's a concern which is applicable throughout the application and it can also affect 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. 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. Issues in which we are interested define our concerns.

Q.48 What is Join point? This may represent a point in your application, where we can plug-in AOP aspect. You can also say, it is also the actual place in application where an action will be taken using Spring AOP framework.

Q.49 What is Advice? This can be said as the actual action, which has to be taken either before or after the method execution. This is the piece of code which is invoked during program execution by Spring AOP framework.

Spring Interview Questions Last Updated: November 2016 | Page 18 of 19

Q.50 What is Pointcut? This is a set of one or more joinpoints, where an advice should be executed. We can also specify pointcuts with the use of patterns or expressions, as we will see in our AOP examples.

Q.51 What is Target object? The Target object is which is being advised by one or more aspects, this object may always be a proxy object. Also this is referred to as an advised object.

Q.52 What is Weaving? Weaving is the process of linking aspects, with other objects or application types and create an advised object.

Q.53 What are the types of advice? Spring aspects can work with five kinds of advice mentioned below: ● after: Runs the advice after the a method execution regardless of its outcome. ● before: Runs the advice before the a method execution. ● after-throwing: Runs the advice after the a method execution only if method exits by throwing an exception. ● after-returning: Runs the advice after the a method execution only if method completes successfully. ● around: Runs the advice before and after the advised method is invoked.

Q.54 How JDBC can be used more efficiently in spring framework? We can use JDBC more efficiently with help of a template class, which is provided by spring framework and it is called as JdbcTemplate.

Spring Interview Questions Last Updated: November 2016 | Page 19 of 19