Spring Core Interview Questions - BEHIND JAVA

Spring Core Interview Questions

Share This

What is the use of Spring Framework?

  • Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, and reusable code.
  • Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.
  • Spring is lightweight when it comes to size and transparency. The basic version of Spring framework is around 2MB.
  • The development and configuration of spring framework is easy as compare with others
  • The core features of the Spring Framework can be used in developing any Java application, Also there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promotes good programming practices by enabling a POJO-based programming model.

Explain few of the benefits of using Spring?

Spring targets to make Java EE development easier. Here are the advantages of using it:

  • Spring enables the developers to develop enterprise applications using POJOs (Plain Old Java Object). The benefit of developing the applications using POJO is, that we do not need to have an enterprise container such as an application server but we have the option of using a robust servlet container.
  • Spring provides an abstraction layer on existing technologies like servlets, jsps, jdbc, jndi, rmi, jms and Java mail etc., to simplify the develpment process.
  • Spring comes with some of the existing technologies like ORM framework, logging framework, J2EE and JDK Timers etc, Hence we don’t need to integrate explicitly those technologies.
  • Spring WEB framework has a well-designed web MVC framework, which provides a great alternate to lagacy web framework.
  • Spring can eliminate the creation of the singleton and factory classes.
  • Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (using JTA).
  • Spring framework includes support for managing business objects and exposing their services to the presentation tier components, so that the web and desktop applications can access the same objects.
  • Spring framework has taken the best practice that have been proven over the years in several applications and formalized as design patterns.
  • Spring application can be used for the development of different kind of applications, like standalone applications, standalone GUI applications, Web applications and applets as well.
  • Spring supports both xml and anotation configurations.
  • Spring Framework allows to develop standalone, desktop, 2 tire – n-tire architecture and distributed applications.
  • Spring gives built in middleware services like Connection pooling, Transaction management and etc.,
  • Spring provides a light weight container which can be activated without using webserver or application server.

Explain about spring dependency Injection?

Dependency Injection (DI) is a software design pattern that implements inversion of control for resolving dependencies.

An injection is the passing of a dependency to a dependent object that would use it.

DI is a process whereby objects define their dependencies. The other objects they work with—only through constructor arguments or arguments to a factory method or property—are set on the object instance after it is constructed or returned from a factory method.

The container then injects those dependencies, and it creates the bean. This process is named Inversion of Control (IoC) (the bean itself controls the instantiation or location of its dependencies by using direct construction classes or a Service Locator).

Dependency Injection Performed Two Ways

1. Constructor-Based Dependency Injection

Constructor-based DI is when the container invokes a constructor with a number of arguments, each of which represents a dependency or other class.

Calling a static factory method with particular arguments to construct the bean is approximately equivalent, treating arguments to a constructor and to a static factory method. The following example shows a class that can only be dependency-injected with constructor injection. It is a POJO that has no dependencies on container specific interfaces, base classes, or annotations.

2. Setter-Based Dependency Injection

Setter-based DI is the when the container calls setter methods on your beans after it has invoked a no-argument constructor or no-argument static factory method to instantiate that bean.

The following example shows a class that can only have pure setter injection.

Explain Difference between Setter and Constructor Injection in Spring framework?

  • The fundamental difference between setter and constructor injection, as their name implies is How dependency is injected. Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring's IOC container. On the other hand constructor injection uses constructor to inject dependency on any Spring-managed bean.
  • Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml . Since setter method has name e.g. setReportService() by reading Spring XML config file you know which dependency you are setting. While in constructor injection, since it uses an index to inject the dependency, it's not as readable as setter injection and you need to refer either Java documentation or code to find which index corresponds to which property.
  • Another difference between setter vs constructor injection in Spring and one of the drawback of setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.
  • One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call the constructor, a new object is gets created.

Setter DI vs. Constructor DI in Spring,which one is better?

Constructor injection (from the definition) does not allow you to create circular dependencies between beans. This limitation is actually an advantage of constructor injection - Spring can resolve circular dependencies when setter injection is used without you even noticing.

On the other hand if you use constructor injection CGLIB is not able to create a proxy, forcing you to either use interface-based proxies or a dummy no-arg constructor.

What are the difference between bean factory and applicationContext?

  BeanFactory ApplicationContext
Annotation support No Yes
BeanPostProcessor Registration Manual Automatic
implementation XMLBeanFactory ClassPath/FileSystem/WebXmlApplicationContext
internationalization No Yes
Enterprise services No Yes
ApplicationEvent publication No Yes

What are the different spring bean scopes?

When defining a <bean> you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similarly, if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.

The Spring Framework supports the following five scopes, three of which are available only if you use a web-aware ApplicationContext.

singleton

If a scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

The default scope is always singleton. However, when you need one and only one instance of a bean, you can set the scope property to singleton in the bean configuration file, as shown in the following code snippet

prototype

If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown in the following code snippet

request

This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.

session

This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

global-session

The global session scope is similar to the Session scope and really only makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared among all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are bound to the lifetime of the global portlet Session.

How to use multiple Spring configuration files in one project?

Yes, in large projects, having multiple Spring configurations is recommended to increase maintainability and modularity.

You can load multiple Java-based configuration files:

@Configuration
@Import({MainConfig.class, SchedulerConfig.class})
public class AppConfig {

Or load one XML file that will contain all other configs:

ApplicationContext context = new ClassPathXmlApplicationContext("spring-all.xml");

And inside this XML file you’ll have:

Explain the spring hibernate project configuraion step by step?

1. Create maven web project

Create a maven web project using below command from command prompt.

$ mvn archetype:generate -DgroupId=com.behindjava.app 
       -DartifactId=Spring3HibernateIntegration
       -DarchetypeArtifactId=maven-archetype-webapp 
       -DinteractiveMode=false

Update pom.xml file to include spring and hibernate dependencies. It will also include mysql driver added in project references.

2. Create database schema

Now lets decide out database schema structure because it will be needed when we will write the entity classes in next step.

CREATE TABLE EMPLOYEE
(
    ID          INT PRIMARY KEY AUTO_INCREMENT,
    FIRSTNAME   VARCHAR(30),
    LASTNAME    VARCHAR(30),
    TELEPHONE   VARCHAR(15),
    EMAIL       VARCHAR(30),
    CREATED     TIMESTAMP DEFAULT NOW()
);

3. Write hibernate entity classes

Now its time to write EmployeeEntity. This class will be mapped to Employee table in database using hibernate. JPA will include any class annotated with @Entity in the persistence management setup. You don’t need persistence.xml if you use annotations.

4. Write data access code

Lets write our DAO classes which will be responsible for database interaction. This class will be essentially using the hibernate session factory for database interaction. The session factory implementation will be injected into reference variable at runtime using spring IoC feature.

I have written a manager layer also which seems redundant in this demo due less complexity but it as always considered best practice if you write this. This layer will simply take call from controller and pass this call to dao layer.

5. Spring controller and view files

Spring controller and handler methods will actually be called from spring framework’s dispatcher servlet to process actual application logic.

Now we will write our application’s view layer which is actually a .jsp file.

6. Spring dispatcher servlet

Now the implementation ofcode is complete and now its time to configure the application. Lets start from web.xml. In web.xml, we will configure the front controller for spring framework that is DispatcherServlet.

7. Spring hibernate integration configuration

Lets configure spring framework for hibernate data source, message resources, view resolvers and other such things.

Hibernate configuration becomes simple when using annotation.

8. JDBC Properties

Lets mention jdbc connection properties and message resource properties.

Compare Spring annotation-based DI vs xml configuration?

Libraries, by definition, provide a particular functionality and can be used in various scenarios, not necessarily involving DI. Therefore, using annotations in the library projects we develop ourselves, would create a dependency of the DI framework (Spring in our case) to the library, making the library unusable in non-DI context. Having extra dependencies is not considered a good practice among our team (an in general IMHO).

When we are assembling an application, the application context would define the necessary dependencies. This will simplify dependency tracking as the application becomes the central unit of combining all the referenced components, and usually this is indeed where all the wiring up should happen.

XML is also good for us when providing mock implementations for many components, without recompiling the application modules that will use them. This gives us flexibility when testing running in local or production environment.

In regards to annotations, we decided that we can benefit using them when the injected components will not vary -- for instance only a certain implementation for a component will be used troughout the application.

The annotations will be very useful for small components/applications that will not change or support different implementations of a dependency at once, and that are unlikely to be composed in a different way (for instance using different dependencies for different builds). Simple micro-services would fit in this category.

Small enough components, made up with annotations, can be used right out of the box in different projects, without having the respective applications to cover them in their XML configuration. This would simplify the application dependency wiring for the application and reduce repetitive setups.

However, we agreed that such components should have the dependencies well described in our technical documentation, so that when assembling the entire application, one can have an idea of these dependencies without scrolling through the code, or even loading the module in the IDE.

A negative side effect of annotation-configured components, is that different components could bring clashing transitive dependencies, and again it is up to the final application to resolve the conflicts. When these dependencies are not defined in XML, the conflict resolution approaches become quite limited and straying far from the best practices, if they are at all possible. So, when going with annotations, the component has to be mature enough about what dependencies it is going use.

In general if our dependencies may vary for different scenarios, or a module can be used with different components, we decided to stick to XML. Clearly, there MUST be a right balance between both approaches, and a clear idea for the usages.

An important update regarding the mixed approach. Recently we had a case with a test framework we created for our QA team, which required dependencies from another project. The framework was designed to use the annotation approach and Spring configuration classes, while the referenced project had some xml contexts that we needed to reference. Unfortunately, the test classes (where we used org.testng with spring support) could only work with either the xml or java configuration classes, not mixing both.

This situation illustrates a case where mixing the approaches would clash and clearly, one must be discarded. In our case, we migrated the test framework to use spring xml contexts, but other uses could imply the other way around.

Explain brief history of Spring framework?

Before Spring Framework, the applications were developed by using traditional JEE standards. These standards provided some very great features, like transaction management, messaging, mailing, directory interface etc., but as nothing comes without paying the cost, it also had some drawbacks like:

  • Writing the code was very complex as while writing a component it is required to write a set of XML files, home interfaces, remote/ local interfaces, etc.
  • Whenever a component depended upon another component, it had to look up for the components it depended upon by itself. This component ‘look-up’ happens only by name, so the name of the dependency was hard-coded in the component.
  • As all features like clustering, remoting, etc. were supported, you have to configure them, regardless of the fact that you need them or not. This will make your applications bloated.

All these problems were solved by the introduction of Spring Framework. In October 2002, Rod Johnson, an Australian computer specialist, wrote a book titled Expert One-on-One J2EE Design and Development.

In this book he proposed a simpler solution based on ordinary Java classes (POJO) and dependency injection. He wrote over 30,000 lines of infrastructure code which included a number of reusable java interfaces and classes for developing the application. Around February 2003, Rod, Juergen and Yann started collaborating on the Spring project. The name “Spring” was given as it meant a fresh start after “Winter” of traditional J2EE.

Explain about tight coupling and loose coupling?

Tight Coupling

Tightly coupled object is an object that needs to know quite a bit about other objects and are usually highly dependent on each other's interfaces. Changing one object in a tightly coupled application often requires changes to a number of other objects. In a small application we can easily identify the changes and there is less chance to miss anything. But in large applications these inter-dependencies are not always known by every programmer and there is chance of overlooking changes.

See below code is for tight coupling.

In the above code the Journey class is dependents on Car class to provide service to the end user(main class to call this Journey class).

In the above case Journey class is tightly coupled with Car class it means if any change in the Car class requires Journey class to change. For example if Car class travel() method change to journey() method then you have to change the startJourney() method will call journey() method instead of calling travel() method.

See below code,

The best example of tight coupling is RMI(Remote Method Invocation)(Now a days every where using web services and SOAP instead of using RMI, it has some disadvantages).

Loose Coupling

Loose coupling is a design goal that seeks to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component. Loose coupling is much more generic concept intended to increase the flexibility of system, make it more maintainable and makes the entire framework more stable.

Below code is an example of loose coupling,

In the above example, Journey and Car objects are loosely coupled. It means Vehicle is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.

The examples of Loose coupling are Interface, JMS, Spring IOC(Dependency Injection, it can reduce the tight coupling).

Advantages Of Loose coupling

A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change. With too a tight coupled architecture, many parts will need to change and it will be difficult to identify exactly which parts will be affected. In short,

  • It improves the testability.
  • It helps you follow the GOF principle of program to interfaces, not implementations.
  • The benefit is that it's much easier to swap other pieces of code/modules/objects/components when the pieces are not dependent on one another.
  • It's highly changeable. One module doesn't break other modules in unpredictable ways.

Does Spring singleton beans are thread-safe?

No, Spring singleton beans are not thread-safe. Singleton doesn't mean bean would be thread-safe.

What is the difference in Spring MVC and Spring core?

The Spring MVC is part of the Spring framework which helps you to develop Java web application using model web controller pattern, while Spring Core provides the Dependency injection and Inversion of Control. The Spring Container is part of Spring core.

Both functionalities come in different JAR files. If you are developing just a core Java application using Spring then you just need Spring Core but if you are developing Web application then you need spring-mvc.jar as well. See Introduction to Spring MVC to learn more about Spring framework architecture and components.

How to configure DispatcherServlet in Spring?

The DispatcherServlet is like any other Servlet class and it has to be declared inside the deployment descriptor or web.xml file as shown below:

Its URL pattern is usually "*" so that all incoming request should go through Dispatcher servlet as shown below:

I haven't shown here but, DispatcherServlet is also usually preloaded using the load-on-startup tag of the deployment descriptor. You can give zero or positive value on this tag to pre-load a servlet, otherwise, the servlet will only be loaded when a request will arise.

If your servlet does a lot of job on initialization e.g. DispatcherServlet which initializes all the beans declared in its web context e.g. controllers, view resolvers, and mapping handlers then it could slow down the response time.

Btw, it's not the only way to declare DispatcherServlet in Spring MVC. From Spring 3.2 and Servlet 3.0 specification, you can programmatically declare DispatcherServlet using ServletContainerInitializer interface. This is a Servlet 3,0 feature which allows Servlet 3.0 compliant containers e.g. Tomcat 7 or higher to scan and load any class which implements this interface.

Spring provides an implementation of this interface as SpringServletContainerInitializer and a convenient class called AbstractAnnotationConfigDispatcherServletInitialzer in Spring 3.2 to configure DispatcherServlet without deployment descriptor.

How dispatcher servlet works internally?

DispatcherServlet wears many hats in Spring. It acts as a front controller and provides a single entry point for the application. It then uses handler mappings and handler adapters to map a request to the Spring MVC controllers. It uses @Controller and @RequestMapping annotation for that purpose.

Once the request is processed by Spring MVC controller, it returns a logical view name instead of the view. Though, you can even configure Controler's handler methods to not return any View name by declaring return type as void. You can even use @ResponseBody annotation in the case of REST to directly write the output to the HTTP response body. See REST with Spring course by Eugen to learn more about developing RESTful web services using Spring MVC.

When DispatherServlet receives view name, it consults the ViewResolver to find the right view. There is a chain of ViewResolver is maintained at Spring MVC framework. They try to resolve the logical view name into a Physical resource e.g. a JSP page or a FreeMaker or Velocity template.

The ViewResolver are invoked in an order, if first in the chain not able to resolve the view then it returns null and next ViewResolver in the chain is consults. Once the right view is found, DispatcherServlet forwards the request along with Model data to the View for rendering e.g. a JSP page.

By default, DispatcherServlet uses InternalResourceViewResolver which uses prefix and suffix to convert a logical view name e.g. "home" to /WEB-INF/home.jsp. The View interface also has getContentType() method, which returns content type the view produces (JstlView has text/html). This is usually the default content type for requests handled by the dispatcher servlet in Spring.

In short, DispatcherServlet is used following things in Spring MVC

  • receives all request as Front Controller and provides a single entry point to the application
  • mapping requests to correct Spring MVC controller
  • Consulting ViewResolvers to find correct View
  • forwarding request to chosen View for rendering
  • returning the response to the client
  • creates web-context to initialize the web specific beans e.g. controllers, view resolvers and handler mapping

That's all about what is the use of DispatcherServlet in Spring framework. It's is one of the key components of Spring MVC which is used to receive all incoming request and forward them to right controllers for actual processing. It finds the right controllers by using handler mappings e.g. SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping, which check if the bean name is same as view name and the bean implements the View interface.

If you are using annotations then it can also use @Controller and @RequestMapping annotations to find the right controller to process a particular request. Once the request is processed by controller it returns a logical view name to DispatcherServlet.

The DispatcherServlet then consults ViewResolver and LocalResolvers to find the right View to render the output. Once the correct View is chosen, it forwards the request to the View for rendering the response.

No comments:

Post a Comment

Pages