14 Tips for Writing Spring MVC Controllers

Man writing a Spring MVC Controller

Here are the best tips and tricks for writing Spring MVC Controllers.

In this article, I’m going to share with you some of the fundamental techniques and best practices for writing a controller class with the Spring MVC framework. Typically, in Spring MVC, we write a controller class to handle requests coming from the client.

Then, the controller invokes a business class to process business-related tasks, and then redirects the client to a logical view name, which is resolved by Spring’s dispatcher servlet in order to render results or output. That completes a round trip of a typical request-response cycle.

You may also like: How Spring MVC Really Works

1. Using the @Controller Stereotype

This is the simplest way to create a controller class that can handle one or multiple requests. Just by annotating a class with the @Controller stereotype, for example:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
    @RequestMapping("/")
    public String visitHome() {
        // do something before returning view name
        return "home";
    }
}

As you can see, the visitHome() method handles requests coming to the application’s context path (/) by redirecting to the view named home.

NOTE: the @Controller stereotype can only be used when annotation-driven is enabled in Spring’s configuration file:

<annotation-driven />

When annotation-driven is enabled, the Spring container automatically scans for classes under the package specified in the following statement:

<context:component-scan base-package="net.codejava.spring" />

The classes annotated by the @Controller annotation are configured as controllers. This is most preferable because of its simplicity: There’s no need to declare beans for controllers in the configuration file.

NOTE: By using the @Controller annotation, you can have a multi-actions controller class that is able to serve multiple different requests. For example:

@Controller
public class MultiActionController {
    @RequestMapping("/listUsers")
    public ModelAndView listUsers() {

    }
    @RequestMapping("/saveUser")
    public ModelAndView saveUser(User user) {

    }
    @RequestMapping("/deleteUser")
    public ModelAndView deleteUser(User user) {

    }
}

As you can see in the above controller class, there are three handler methods that process three different requests  /listUsers/saveUser, and /deleteUser, respectively.

2. Implementing the Controller Interface

Another (and maybe classic) way of creating a controller in Spring MVC is having a class implement the Controller interface. For example:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class MainController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        System.out.println("Welcome main");
        return new ModelAndView("main");
    }
}

The implementing class must override the handleRequest() method, which will be invoked by the Spring dispatcher servlet when a matching request comes in. The request URL pattern handled by this controller is defined in the Spring’s context configuration file as follows:

<bean name="/main" class="net.codejava.spring.MainController" />

However, a drawback of this approach is that the controller class cannot handle multiple request URLs.

3. Extending the AbstractController Class

If you want to easily control the supported HTTP methods, session, and content caching. having your controller class extended the AbstractController class is ideal. Consider the following example:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class BigController extends AbstractController {
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        System.out.println("You're big!");
        return new ModelAndView("big");
    }
}

This creates a single-action controller with configurations regarding the supported methods, session, and caching, which can then be specified in the bean declaration of the controller. For example:

<bean name="/big" class="net.codejava.spring.BigController">
    <property name="supportedMethods" value="POST"/>
</bean>

This configuration indicates that only the POST method is supported by this controller’s hander method. For other configuration (session, caching), see AbstractController.

Spring MVC also offers several controller classes designed for specific purposes, including:

4. Specifying URL Mapping for the Handler Method

This is the mandatory task you must do when coding a controller class, which is designed for handling one or more specific requests. Spring MVC provides the @RequestMapping annotation, which is used for specifying URL mapping. For example:

@RequestMapping("/login")

That maps the URL pattern /login to be handled by the annotated method or class. When this annotation is used at the class level, the class becomes a single-action controller. For example:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class SingleActionController {
    @RequestMapping(method = RequestMethod.GET)
    public String sayHello() {
        return "hello";
    }
}

When the @RequestMapping annotation is used at the method level, you can have a multi-action controller. For example:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserController {
    @RequestMapping("/listUsers")
    public String listUsers() {
        return "ListUsers";
    }
    @RequestMapping("/saveUser")
    public String saveUser() {
        return "EditUser";
    }
    @RequestMapping("/deleteUser")
    public String deleteUser() {
        return "DeleteUser";
    }
}

The @RequestMapping annotation can be also used for specifying multiple URL patterns to be handled by a single method. For example:

@RequestMapping({"/hello", "/hi", "/greetings"})

In addition, this annotation has other properties that may be useful in some cases, e.g. the method property which is covered in the next section.

5. Specifying HTTP Request Methods for the Handler Method

You can specify which HTTP method (GET, POST, PUT, …) is supported by a handler method using the method property of the  @RequestMapping annotation. Here’s an example:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String viewLogin() {
        return "LoginForm";
    }
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String doLogin() {
        return "Home";
    }
}

As you can see, this controller has two methods that handle the same URL pattern /login, but the former is for the GET method and the latter is for the POST method.

For more information about using the @RequestMapping annotation, see @RequestMapping annotation.

6. Mapping Request Parameters to Handler Method

One of the cool features of Spring MVC is that you can retrieve request parameters as regular parameters of the handler method by using the  @RequestParam annotation. This is a good way to decouple the controller from the  HttpServletRequest interface of the Servlet API.

Let’s look at various examples. Consider the following method:

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(@RequestParam String username,
                      @RequestParam String password) {

}

Spring binds the method parameters username and password to the HTTP request parameters with the same names. That means you can invoke a URL as follows (if the request method is GET):

http://localhost:8080/spring/login?username=scott&password=tiger

Type conversion is also done automatically. For example, if you declare a parameter of type integer as follows:

@RequestParam int securityNumber

Then, Spring will automatically convert value of the request parameter (String) to the specified type (integer) in the handler method.

In case the parameter name is different than the variable name, you can specify the actual name of the parameter as follows:

@RequestParam("SSN") int securityNumber

The @RequestParam annotation also has two additional attributes, which might be useful in some cases. The required attribute specifies whether the parameter is mandatory or not. For example:

@RequestParam(required = false) String country

That means the parameter country is optional; hence, it can be missing from the request. In the above example, the variable country will be null if there is no such parameter present in the request.

Another attribute is defaultValue, which can be used as a fallback value when the request parameter is empty. For example:

@RequestParam(defaultValue = "18") int age

Spring also allows us to access all parameters as a Map object if the method parameter is of type  Map<String, String>. For example:

doLogin(@RequestParam Map<String, String> params)

Then the map params contains all request parameters in the form of key-value pairs. For more information about using the @RequestParam annotation, see @RequestParam annotation.

7. Returning Model and View

After business logic is processed, a handler method should return a view, which is then resolved by the Spring’s dispatcher servlet. Spring allows us to return either a String or a ModelAndView object from the handler method. In the following example, the handler method returns a String and represents a view named LoginForm:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String viewLogin() {
    return "LoginForm";
}

That’s the simplest way of returning a view name. But if you want to send additional data to the view, you must return a ModelAndView object. Consider the following handler method:

@RequestMapping("/listUsers")
public ModelAndView listUsers() {
    List<User> listUser = new ArrayList<>();
    // get user list from DAO...
    ModelAndView modelView = new ModelAndView("UserList");
    modelView.addObject("listUser", listUser);
    return modelView;
}

As you can see, this handler method returns a ModelAndView object that holds the view name UserList and a collection of User objects, which can be used in the view.

Spring is also very flexible, as you can declare the ModelAndView object as a parameter of the handler method instead of creating a new one. Thus, the above example can be re-written as follows:

@RequestMapping("/listUsers")
public ModelAndView listUsers(ModelAndView modelView) {
    List<User> listUser = new ArrayList<>();
    // get user list from DAO...
    modelView.setViewName("UserList");
    modelView.addObject("listUser", listUser);
    return modelView;
}

You can learn more about the ModelAndView class by visiting: ModelAndView class.

8. Putting Objects Into the Model

In an application that follows the MVC architecture, the controller (C) should pass data into the model (M), which is then used in the view (V). As we see in the previous example, the addObject() method of the ModelAndView class is for putting an object to the model, in form of name-value pair:

modelView.addObject("listUser", listUser);
modelView.addObject("siteName", new String("CodeJava.net"));
modelView.addObject("users", 1200000);

Again, Spring is very flexible. You can declare a parameter of type Map in the handler method; Spring uses this map to store objects for the model. Let’s see another example:

@RequestMapping(method = RequestMethod.GET)
public String viewStats(Map<String, Object> model) {
    model.put("siteName", "CodeJava.net");
    model.put("pageviews", 320000);
    return "Stats";
}

This is even simpler than using the ModelAndView object. Depending on your taste, you can use either Map or ModelAndView object. Thanks for the flexibility of Spring.

9. Redirection in Handler Method

In case you want to redirect the user to another URL if a condition is met, just append  redirect:/ before the URL. The following code snippet gives an example:

// check login status....
if (!isLogin) {
    return new ModelAndView("redirect:/login");
}
// return a list of Users

In the above code, the user will be redirected to the  /login URL if it is not logged in.

10. Handling Form Submission and Form Validation

Spring makes it easy to handle form submission by providing the  @ModelAttribute annotation for binding form fields to a form backing object, and the BindingResult interface for validating form fields. The following code snippet shows a typical handler method that is responsible for handling and validating form data:

@Controller
public class RegistrationController {
    @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
    public String doRegister(
        @ModelAttribute("userForm") User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // form validation error
        } else {            
            // form input is OK
        }
        // process registration...
        return "Success";
    }
}

Learn more about the  @ModelAttribute annotation and the BindingResult interface from Spring’s official documentation:

11. Handling File Upload

Spring also makes it easy to handle file upload within a handler method, by automatically binding upload data to an array of CommonsMultipartFile objects. Spring uses Apache Commons FileUpload as the underlying multipart resolver.

The following code snippet shows how easy it is to get files uploaded from the client:

@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
public String handleFileUpload(
        @RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
    for (CommonsMultipartFile aFile : fileUpload){
        // stores the uploaded file
        aFile.transferTo(new File(aFile.getOriginalFilename()));
    }
    return "Success";
}

You can learn the complete solution for handling file upload with Spring MVC by following this Spring MVC File Upload Tutorial.

12. Autowiring Business Classes in the Controller

A controller should delegate the processing of business logic to relevant business classes. For this purpose, you can use the @Autowired annotation to let Spring automatically inject the actual implementation of a business class to the controller. Consider the following code snippet of a controller class:

@Controller
public class UserController {
    @Autowired
    private UserDAO userDAO;
    public String listUser() {
        // handler method to list all users
        userDAO.list();
    }
    public String saveUser(User user) {
        // handler method to save/update a user
        userDAO.save(user);
    }
    public String deleteUser(User user) {
        // handler method to delete a user
        userDAO.delete(user);
    }
    public String getUser(int userId) {
        // handler method to get a user
        userDAO.get(userId);
    }
}

Here, all business logic related to User management is provided by an implementation of the UserDAO interface. For example:

interface UserDAO {
    List<User> list();
    void save(User user);
    void checkLogin(User user);
}

By using the @Autowired annotation, the handler methods can delegate tasks to the business class, as we can see in the above example:

List<User> listUser = userDAO.list();

For more information about the  @Autowired annotation, see Annotation Type Autowired.

13. Accessing HttpServletRequest and HttpServletResponse

In some cases, you need to directly access the HttpServletRequest or HttpServletResponse objects within a handler method. By the flexibility of Spring, just add a relevant parameter to the handler method. For example:

@RequestMapping("/download")
public String doDownloadFile(
        HttpServletRequest request, HttpServletResponse response) {
    // access the request
    // access the response
    return "DownloadPage";
}

Spring detects and automatically injects the HttpServletRequest and HttpServletResponse objects into the method. Then, you can access the request and response such as getting InputStreamOutputStream, or returning a specific HTTP code.

14. Following the Single Responsibility Principle

Finally, there are two good practices you should follow when designing and coding controllers in Spring MVC:

  • A controller class should not execute business logic. Instead, it should delegate business processing to relevant business classes. This keeps the controller focusing on its designed responsibility is to control workflows of the application. For example:
@Controller
public class UserController {
    @Autowired
    private UserDAO userDAO;
    public String listUser() {
        // handler method to list all users
        userDAO.list();
    }
    public String saveUser(User user) {
        // handler method to save/update a user
        userDAO.save(user);
    }
    public String deleteUser(User user) {
        // handler method to delete a user
        userDAO.delete(user);
    }
    public String getUser(int userId) {
        // handler method to get a user
        userDAO.get(userId);
    }
}
  • Create each separate controller for each business domain. For example, UserController for controlling workflows of the user management, OrderController for controlling workflows of order processing, etc. For example:
@Controller
public class UserController {

}
@Controller
public class ProductController {

}
@Controller
public class OrderController {

}
@Controller
public class PaymentController {

}

There you have it! I have shared 14 tips that will help you write controller classes in Spring MVC properly and efficiently. However, that’s not the end. If you have other tips or suggestions, feel free to share your thoughts in the comments.

Further Reading

How Spring MVC Really Works

Spring MVC and Java-Based Configuration

Spring Framework: @RestController Vs. @Controller

Spring Interview Questions

General Questions – Spring Interview Questions

1. What are the major features in different versions of Spring Framework?

Features of Spring Framework

Version Logo Feature
Spring 2.5 spring 2.5 logo - Spring Interview Questions - Edureka! This version was released in 2007. It was the first version which supported annotations.
Spring 3.0 spring 3.0 logo - Spring Interview Questions - Edureka! This version was released in 2009. It made full-fledged use of improvements in Java5 and also provided support to JEE6.
Spring 4.0 Spring 4.0 logo - Spring Interview Questions - Edureka!  This version was released in 2013. This was the first version to provide full support to Java 8.

2. What is a Spring Framework?

  • Spring logo - Spring Interview Questions - Edureka!Spring is a powerful open source, application framework created to reduce the complexity of enterprise application development.
  • It is light-weighted and loosely coupled.
  • It has layered architecture, which allows you to select the components to use, while also providing a cohesive framework for J2EE application development.
  • Spring framework is also called the framework of frameworks as it provides support to various other frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc.

3. List the advantages of Spring Framework.

  • Because of Spring Frameworks layered architecture, you can use what you need and leave which you don’t.
  • Spring Framework enables POJO (Plain Old Java Object) Programming which in turn enables continuous integration and testability.
  • JDBC is simplified due to Dependency Injection and Inversion of Control.
  • It is open-source and has no vendor lock-in.

4. What are the different features of Spring Framework?

Following are some of the major features of Spring Framework :

  • Lightweight: Spring is lightweight when it comes to size and transparency.
  • Inversion of control (IOC): The objects give their dependencies instead of creating or looking for dependent objects. This is called Inversion Of Control.
  • Aspect oriented Programming (AOP): Aspect oriented programming in Spring supports cohesive development by separating application business logic from system services.
  • Container: Spring Framework creates and manages the life cycle and configuration of the application objects.
  • MVC Framework: Spring Framework’s MVC web application framework is highly configurable. Other frameworks can also be used easily instead of Spring MVC Framework.
  • Transaction Management: Generic abstraction layer for transaction management is provided by the Spring Framework. Spring’s transaction support can be also used in container less environments.
  • JDBC Exception Handling: The JDBC abstraction layer of the Spring offers an exception hierarchy, which simplifies the error handling strategy.

5. How many modules are there in Spring Framework and what are they?

There are around 20 modules which are generalized into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test.Spring Framework Architecture - Spring Interview Questions - Edureka!

  • Spring Core Container – This layer is basically the core of Spring Framework. It contains the following modules :
  1. Spring Core
  2. Spring Bean
  3. SpEL (Spring Expression Language)
  4. Spring Context
  • Data Access/Integration – This layer provides support to interact with the database. It contains the following modules :
  1. JDBC (Java DataBase Connectivity)
  2. ORM (Object Relational Mapping)
  3. OXM (Object XML Mappers)
  4. JMS (Java Messaging Service)
  5. Transaction
  • Web – This layer provides support to create web application. It contains the following modules :
  1. Web
  2. Web – MVC
  3. Web – Socket
  4. Web – Portlet
  • Aspect Oriented Programming (AOP) – In this layer you can use Advices, Pointcuts etc., to decouple the code.
  • Instrumentation – This layer provides support to class instrumentation and classloader implementations.
  • Test – This layer provides support to testing with JUnit and TestNG.

Few Miscellaneous modules are given below:

  • Messaging – This module provides support for STOMP. It also supports an annotation programming model that is used for routing and processing STOMP messages from WebSocket clients.
  • Aspects – This module provides support to integration with AspectJ.

6. What is a Spring configuration file?xml file - Spring Interview Questions - Edureka!

A Spring configuration file is an XML file. This file mainly contains the classes information. It describes how those classes are configured as well as introduced to each other. The XML configuration files, however, are verbose and more clean. If it’s not planned and written correctly, it becomes very difficult to manage in big projects.

7. What are the different components of a Spring application?

A Spring application, generally consists of following components:

  • Interface: It defines the functions.
  • Bean class: It contains properties, its setter and getter methods, functions etc.
  • Spring Aspect Oriented Programming (AOP): Provides the functionality of cross-cutting concerns.
  • Bean Configuration File: Contains the information of classes and how to configure them.
  • User program: It uses the function.

8. What are the various ways of using Spring Framework?spring app - Spring Interview Questions - Edureka!

Spring Framework can be used in various ways. They are listed as follows:

  1.  As a Full-fledged Spring web application.
  2. As a third-party web framework, using Spring Frameworks middle-tier.
  3.  For remote usage.
  4. As Enterprise Java Bean which can wrap existing POJOs (Plain Old Java Objects).

The next section of Spring Interview Questions is on Dependency Injection and IoC container.

Dependency Injection/ IoC Container – Spring Interview Questions

9. What is Spring IOC Container?

ioc - Spring Interview Questions - Edureka!

At the core of the Spring Framework, lies the Spring container. The container creates the object, wires them together, configures them and manages their complete life cycle. The Spring container makes use of Dependency Injection to manage the components that make up an application. The container receives instructions for which objects to instantiate, configure, and assemble by reading the configuration metadata provided. This metadata can be provided either by XML, Java annotations or Java code.

10. What do you mean by Dependency Injection? 

In Dependency Injection, you do not have to create your objects but have to describe how they should be created. You don’t connect your components and services together in the code directly, but describe which services are needed by which components in the configuration file. The IoC container will wire them up together.

11. In how many ways can Dependency Injection be done?

In general, dependency injection can be done in three ways, namely :

  • Constructor Injection
  • Setter Injection
  • Interface Injection

In Spring Framework, only constructor and setter injections are used.

12. Differentiate between constructor injection and setter injection.

Constructor Injection vs Setter Injection

Constructor Injection Setter Injection
There is no partial injection. There can be partial injection.
It doesn’t override the setter property. It overrides the constructor property.
It will create a new instance if any modification is done. It will not create new instance if any modification is done.
It works better for many properties. It works better for few properties.

13. How many types of IOC containers are there in spring?

  1. BeanFactory: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients.
  2. ApplicationContext: The ApplicationContext interface is built on top of the BeanFactory interface. It provides some extra functionality on top BeanFactory.

14. Differentiate between BeanFactory and ApplicationContext.

BeanFactory vs ApplicationContext

BeanFactory ApplicationContext
It is an interface defined in org.springframework.beans.factory.BeanFactory It is an interface defined in org.springframework.context.ApplicationContext
It uses Lazy initialization It uses Eager/ Aggressive initialization
It explicitly provides a resource object using the syntax It creates and manages resource objects on its own
It doesn’t supports internationalization It supports internationalization
It doesn’t supports annotation based dependency It supports annotation based dependency

15.  List some of the benefits of IoC.

Some of the benefits of IoC are:

  • It will minimize the amount of code in your application.
  • It will make your application easy to test because it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.
  • It promotes loose coupling with minimal effort and least intrusive mechanism.
  • It supports eager instantiation and lazy loading of the services.

Let’s move on to the next section of Spring Interview Questions, that is Spring Beans Interview Questions.

Spring Beans – Spring Interview Questions

16. Explain Spring Beans?

  • They are the objects that form the backbone of the user’s application.
  • Beans are managed by the Spring IoC container.
  • They are instantiated, configured, wired and managed by a Spring IoC container
  • Beans are created with the configuration metadata that the users supply to the container.Bean generation - Spring Interview Questions - Edureka!

17. How configuration metadata is provided to the Spring container?

Configuration metadata can be provided to Spring container in following ways:

  • XML-Based configuration: In Spring Framework, the dependencies and the services needed by beans are specified in configuration files which are in XML format. These configuration files usually contain a lot of bean definitions and application specific configuration options. They generally start with a bean tag. For example:
1
2
3
<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">
 <property name="name" value="Edureka"></property>
</bean>
  • Annotation-Based configuration: Instead of using XML to describe a bean wiring, you can configure the bean into the component class itself by using annotations on the relevant class, method, or field declaration. By default, annotation wiring is not turned on in the Spring container. So, you need to enable it in your Spring configuration file before using it. For example:
1
2
3
4
<beans>
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>
  • Java-based configuration: The key features in Spring Framework’s new Java-configuration support are @Configuration annotated classes and @Bean annotated methods.

1. @Bean annotation plays the same role as the <bean/> element. 

2.@Configuration classes allows to define inter-bean dependencies by simply calling other @Bean methods in the same class.

For example:

1
2
3
4
5
6
7
@Configuration
public class StudentConfig
{
@Bean
public StudentBean myStudent()
{ return new StudentBean(); }
}

18. How many bean scopes are supported by Spring?

The Spring Framework supports five scopes. They are:

  • Singleton: This provides scope for the bean definition to single instance per Spring IoC container.
  • Prototype: This provides scope for a single bean definition to have any number of object instances.
  • Request: This provides scope for a bean definition to an HTTP-request.
  • Session: This provides scope for a bean definition to an HTTP-session.
  • Global-session: This provides scope for a bean definition to an Global HTTP-session.

The last three are available only if the users use a web-aware ApplicationContext.

19. What is the Bean life cycle in Spring Bean Factory Container?

Bean life cycle in Spring Bean Factory Container is as follows:

  1. The Spring container instantiates the bean from the bean’s definition in the XML file.
  2. Spring populates all of the properties using the dependency injection, as specified in the bean definition.
  3. The factory calls setBeanName() by passing the bean’s ID, if the bean implements the BeanNameAware interface.
  4. The factory calls setBeanFactory() by passing an instance of itself, if the bean implements the BeanFactoryAware interface.
  5. preProcessBeforeInitialization() methods are called if there are any BeanPostProcessors associated with the bean.
  6. If an init-method is specified for the bean, then it will be called.
  7. Finally, postProcessAfterInitialization() methods will be called if there are any BeanPostProcessors associated with the bean.

To understand it in better way check the below diagram:

beanLifeCycle - Spring Interview Questions - Edureka!

20. Explain inner beans in Spring.

A bean can be declared as an inner bean only when it is used as a property of another bean. For defining a bean, the Spring’s XML based configuration metadata provides the use of <bean> element inside the <property> or <constructor-arg>. Inner beans are always anonymous and they are always scoped as prototypes. For example, let’s say we have one Student class having reference of Person class. Here we will be creating only one instance of Person class and use it inside Student.

Here’s a Student class followed by bean configuration file:

Student.java

1
2
3
4
5
6
7
8
9
10
11
public class Student
{
private Person person;
//Setters and Getters
}
public class Person
{
private String name;
private String address;
//Setters and Getters
}

studentbean.xml

1
2
3
4
5
6
7
8
9
<bean id=“StudentBean" class="com.edureka.Student">
<property name="person">
<!--This is inner bean -->
<bean class="com.edureka.Person">
<property name="name" value=“Scott"></property>
<property name="address" value=“Bangalore"></property>
</bean>
</property>
</bean>

21. Define Bean Wiring.

When beans are combined together within the Spring container, it’s called wiring or bean wiring. The Spring container needs to know what beans are needed and how the container should use dependency injection to tie the beans together, while wiring beans.

bean wiring - Spring Framework Interview Questions - Edureka!

22. What do you understand by auto wiring and name the different modes of it?

The Spring container is able to autowire relationships between the collaborating beans. That is, it is possible to let Spring resolve collaborators for your bean automatically by inspecting the contents of the BeanFactory.
Different modes of bean auto-wiring are:

  1. no: This is default setting which means no autowiring. Explicit bean reference should be used for wiring.
  2. byName: It injects the object dependency according to name of the bean. It matches and wires its properties with the beans defined by the same names in the XML file.
  3. byType: It injects the object dependency according to type. It matches and wires a property if its type matches with exactly one of the beans name in XML file.
  4. constructor: It injects the dependency by calling the constructor of the class. It has a large number of parameters.
  5. autodetect: First the container tries to wire using autowire by constructor, if it can’t then it tries to autowire by byType.

23. What are the limitations with auto wiring?

Following are some of the limitations you might face with auto wiring:

  • Overriding possibility: You can always specify dependencies using <constructor-arg> and <property> settings which will override autowiring.
  •  Primitive data type: Simple properties such as primitives, Strings and Classes can’t be autowired.
  • Confusing nature: Always prefer using explicit wiring because autowiring is less precise.

In the next section, we will discuss on Spring Annotations Interview Questions.

Spring Annotations – Spring Interview Questions

24. What do you mean by  Annotation-based container configuration?

Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. It acts as an alternative to XML setups. For example:

1
2
3
4
5
6
7
@Configuration
public class AnnotationConfig
{
@Bean
public MyDemo myDemo()
 { return new MyDemoImpll(); }
}

25. How annotation wiring can be turned on in Spring?

By default, Annotation wiring is not turned on in the Spring container. Thus, to use annotation based wiring we must enable it in our Spring configuration file by configuring <context:annotation-config/> element. For example:

1
2
3
4
<beans xmlns="<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a&gt;" xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a&gt;" xmlns:context="<a href="http://www.springframework.org/schema/context">http://www.springframework.org/schema/context</a&gt;">
<context:annotation-config/>
<beans ………… />
</beans>

26. What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?annotations - Spring Framework Tutorial - Edureka!

@Component: This marks a java class as a bean. It is a generic stereotype for any Spring-managed component. The component-scanning mechanism of spring now can pick it up and pull it into the application context.

@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the Dependency Injection container.

@Service: This annotation is a specialization of the component annotation. It doesn’t provide any additional behavior over the @Component annotation. You can use @Service over @Component in service-layer classes as it specifies intent in a better way.

@Repository: This annotation is a specialization of the @Component annotation with similar use and functionality. It provides additional benefits specifically for DAOs. It imports the DAOs into the DI container and makes the unchecked exceptions eligible for translation into Spring DataAccessException.

27. What do you understand by @Required annotation?

@Required is applied to bean property setter methods. This annotation simply indicates that the affected bean property must be populated at the configuration time with the help of an explicit property value in a bean definition or with autowiring. If the affected bean property has not been populated, the container will throw BeanInitializationException.

For example:

1
2
3
4
5
6
7
8
9
public class Employee
{
private String name;
@Required
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }
}

28. What do you understand by @Autowired annotation?

The @Autowired annotation provides more accurate control over where and how autowiring should be done. This annotation is used to autowire bean on the setter methods, constructor, a property or methods with arbitrary names or multiple arguments. By default, it is a type driven injection.

For Example:

1
2
3
4
5
6
7
8
9
public class Employee
{
private String name;
@Autowired
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }
}

29. What do you understand by @Qualifier annotation?

When you create more than one bean of the same type and want to wire only one of them with a property  you can use the @Qualifier annotation along with @Autowired to remove the ambiguity by specifying which exact bean should be wired.

For example, here we have two classes, Employee and EmpAccount respectively. In EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.

Employee.java

1
2
3
4
5
6
7
8
9
public class Employee
{
private String name;
@Autowired
public void setName(String name)
{ this.name=name; }
public string getName()
{ return name; }
}

EmpAccount.java

1
2
3
4
5
6
7
8
9
10
public class EmpAccount
{
private Employee emp;
@Autowired
@Qualifier(emp1)
public void showName()
{
System.out.println(“Employee name : ”+emp.getName);
}
}

30.  What do you understand by @RequestMapping annotation?

@RequestMapping annotation is used for mapping a particular HTTP request method to a specific class/ method in controller that will be handling the respective request. This annotation can be applied at both levels:

  • Class level : Maps the URL of the request
  • Method level: Maps the URL as well as HTTP request method

Next section of Spring Interview Questions is on Data Access.

Data Access – Spring Interview Questions

31. Describe Spring DAO support?

The Data Access Object (DAO) support in Spring makes it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies easily. It also allows you to code without worrying about catching exceptions that are specific to each of these technology.

32. Name the exceptions thrown by the Spring DAO classes.

See the below diagram, it depicts all the Spring DAO classes in the hierarchical order.

DAO classes - dao - Spring Framework Interview Questions - Edureka!

33.  Which classes are present in spring JDBC API?

Classes present in JDBC API are as follows:

  1. JdbcTemplate
  2. SimpleJdbcTemplate
  3. NamedParameterJdbcTemplate
  4. SimpleJdbcInsert
  5. SimpleJdbcCall

34. What are the ways by which Hibernate can be accessed using Spring?

There are two ways by which we can access Hibernate using Spring:

  1. Inversion of Control with a Hibernate Template and Callback
  2. Extending HibernateDAOSupport and Applying an AOP Interceptor node

35. Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:

  1. Programmatic transaction management: In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.
  2. Declarative transaction management: In this, the transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.

36. What are the different ORM’s supported by Spring?

Different ORM’s supported by Spring are depicted via the below diagram:

orms - Spring Framework Interview Questions - Edureka!The next section of Spring interview questions discusses on Spring AOP Interview Questions.

Aspect Oriented Programming (AOP) – Spring Interview Questions

37. Describe AOP.

Aspect-oriented programming or AOP is a programming technique which allows programmers to modularize crosscutting concerns or behavior that cuts across the typical divisions of responsibility. Examples of cross-cutting concerns can be logging and transaction management. The core of AOP is an aspect. It encapsulates behaviors that can affect multiple classes into reusable modules.

AOP - Spring Framework Interview Questions - Edureka!

38. What do you mean by Aspect?

Aspect is a modularization of concern which cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. Aspects are implemented using regular classes or regular classes annotated with the @Aspect annotation in Spring Framework.

39. Explain JoinPoint.

A point during the execution of a program is called JoinPoint, such as the execution of a method or the handling of an exception. In Spring AOP, a joinpoint always represents a method execution.

40. What is an Advice?

An Action taken by an aspect at a particular joinpoint is known as an Advice. Spring AOP uses an advice as an interceptor, maintaining a chain of interceptors “around” the join point.

advice - Spring Framework Interview Questions - Edureka!

41. What are the different types of Advices?

Different types of Advices in Spring AOP are:

  1. Before: These types of advices execute before the joinpoint methods and are configured using @Before annotation mark.
  2. After returning: These types of advices execute after the joinpoint methods completes executing normally and are configured using @AfterReturning annotation mark.
  3. After throwing:  These types of advices execute only if joinpoint method exits by throwing an exception and are configured using @AfterThrowing annotation mark.
  4. After (finally): These types of advices execute after a joinpoint method, regardless of the method’s exit whether normally or exceptional return and are configured using @After annotation mark.
  5. Around: These types of advices execute before and after a joinpoint and are configured using @Around annotation mark.

42. Point out the difference between concern and cross-cutting concern in Spring AOP?

The concern is the behavior we want to have in a particular module of an application. It can be defined as a functionality we want to implement.

The cross-cutting concern is a concern which is applicable throughout the application. This affects the entire application. For example, logging, security and data transfer are the concerns needed in almost every module of an application, thus they are the cross-cutting concerns.

cross cutting concern vs concern - Spring Framework Interview Questions - Edureka!

43. What are the different AOP implementations?

Different AOP implementations are depicted by the below diagram:

AOP Implementations - Spring Framework Interview Questions - Edureka!

44. What are the difference between Spring AOP and AspectJ AOP?

Spring AOP vs AspectJ AOP

Spring AOP AspectJ AOP
Runtime weaving through proxy is done Compile time weaving through AspectJ Java tools is done
It supports only method level PointCut It suports field level Pointcuts
It is DTD based It is schema based and Annotation configuration

45. What do you mean by Proxy in Spring Framework?

An object which is created after applying advice to a target object is known as a Proxy. In case of client objects the target object and the proxy object are the same.

proxy - Spring Framework Interview Questions - Edureka!

46. In Spring, what is Weaving?

The process of linking an aspect with other application types or objects to create an advised object is called Weaving. In Spring AOP, weaving is performed at runtime. Refer the below diagram:

Weaving - Spring Framework Interview Question - Edureka!The last section of Spring interview questions is on Spring MVC Interview Questions.

MVC (Model-View-Controller) – Spring Interview Questions

47. What do you mean by Spring MVC framework?

The Spring web MVC framework provides model-view-controller architecture and ready to use components that are used to develop flexible and loosely coupled web applications. The MVC pattern helps in separating the different aspects of the application like input logic, business logic and UI logic, while providing a loose coupling between all these elements.

48. Describe DispatcherServlet.

The DispatcherServlet is the core of Spring Web MVC framework. It handles all the HTTP requests and responses. The DispatcherServlet receives the entry of handler mapping from the configuration file and forwards the request to the controller. The controller then returns an object of Model And View. The DispatcherServlet checks the entry of view resolver in the configuration file and calls the specified view component.

dispatcherServlet - Spring Framework Interview Questions - Edureka!

49. Explain WebApplicationContext.

The WebApplicationContext is an extension of the plain ApplicationContext. It has some extra features that are necessary for web applications. It differs from a normal ApplicationContext in terms of its capability of resolving themes and in deciding which servlet it is associated with.

50. In Spring MVC framework, what is controller?

Controllers provide access to the application behavior. These behaviors are generally defined through a service interface. Controllers interpret the user input and transform it into a model which is represented to the user by the view. In Spring, controller is implemented in a very abstract way. It also enables you to create a wide variety of controllers.

controller - Spring Framework Interview Questions - Edureka!

 

I hope this set of Spring Interview Questions and Answers will help you in preparing for your interviews. All the best!

Top 10 Spring Boot Interview Questions

25+ Spring Boots Interview Questions

In this article, we will discuss some top 10 interview questions in Spring Boot. These questions are a bit tricky and trending heavily, nowadays, in the job market.

1) What does the @SpringBootApplication annotation do internally?

As per the Spring Boot doc, the @SpringBootApplication annotation is equivalent to using @Configuration@EnableAutoConfiguration, and @ComponentScan with their default attributes. Spring Boot enables the developer to use a single annotation instead of using multiple. But, as we know, Spring provided loosely coupled features that we can use for each individual annotation as per our project needs.

2) How to exclude any package without using the basePackages filter?

There are different ways you can filter any package. But Spring Boot provides a trickier option for achieving this without touching the component scan. You can use the exclude attribute while using the annotation  @SpringBootApplication. See the following code snippet:

@SpringBootApplication(exclude= {Employee.class})
public class FooAppConfiguration {}

3) How to disable a specific auto-configuration class?

You can use the exclude attribute of@EnableAutoConfiguration, if you find any specific auto-configuration classes that you do not want are being applied.

//By using “exclude”
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

On the other foot, if the class is not on the classpath, you can use the excludeName attribute of the annotation and specify the fully qualified name instead.

//By using “excludeName”
@EnableAutoConfiguration(excludeName={Foo.class})

Also, Spring Boot provides the facility to control the list of auto-configuration classes to exclude by using the spring.autoconfigure.exclude property. You can add into the application.properties. And you can add multiple classes with comma separated.

//By using property file
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

4) What is Spring Actuator? What are its advantages?

This is one of the most common interview questions in Spring Boot. As per the Spring doc:

“An actuator is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change.”

As we know, Spring Boot provides lots of auto-configuration features that help developers quickly develop production components. But if you think about debugging and how to debug, if something goes wrong, we always need to analyze the logs and dig through the data flow of our application to check to see what’s going on. So, the Spring Actuator provides easy access to those kinds of features. It provides many features, i.e. what beans are created, the mapping in the controller, the CPU usage, etc. Automatically gathering and auditing health and metrics can then be applied to your application.

It provides a very easy way to access the few production-ready REST endpoints and fetch all kinds of information from the web. But by using these endpoints, you can do many things to see here the endpoint docs. There is no need to worry about security; if Spring Security is present, then these endpoints are secured by default using Spring Security’s content-negotiation strategy. Or else, we can configure custom security by the help of RequestMatcher.

5) How to enable/disable the Actuator?

Enabling/disabling the actuator is easy; the simplest way is to enable features to add the dependency (Maven/Gradle) to the spring-boot-starter-actuator, i.e. Starter. If you don’t want the actuator to be enabled, then don’t add the dependency.

Maven dependency:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

6) What is the Spring Initializer?

This may not be a difficult question, but the interviewer always checks the subject knowledge of the candidate. It’s often that you can’t always expect questions that you have prepared. However, this is a very common question asked almost all of the time.

The Spring Initializer is a web application that generates a Spring Boot project with everything you need to start it quickly. As always, we need a good skeleton of the project; it helps you to create a project structure/skeleton properly. You can learn more about the Initializer here.

7) What is a shutdown in the actuator?

Shutdown is an endpoint that allows the application to be gracefully shutdown. This feature is not enabled by default. You can enable this by using management.endpoint.shutdown.enabled=true in your application.properties file. But be careful about this if you are using this.

8) Is this possible to change the port of Embedded Tomcat server in Spring boot?

Yes, it’s possible to change the port. You can use the application.properties file to change the port. But you need to mention “server.port” (i.e. server.port=8081). Make sure you have application.properties in your project classpath; REST Spring framework will take care of the rest. If you mention server.port=0 , then it will automatically assign any available port.

9) Can we override or replace the Embedded Tomcat server in Spring Boot?

Yes, we can replace the Embedded Tomcat with any other servers by using the Starter dependencies. You can use spring-boot-starter-jetty  or spring-boot-starter-undertow as a dependency for each project as you need.

10) Can we disable the default web server in the Spring Boot application?

The major strong point in Spring is to provide flexibility to build your application loosely coupled. Spring provides features to disable the web server in a quick configuration. Yes, we can use the application.properties to configure the web application type, i.e.  spring.main.web-application-type=none.

All the best!

For More : https://www.bipinwebacademy.com/2019/04/spring-boot-interview-questions.html

Using Cache in Spring Boot

Let’s imagine a web application, where for each request received, it must read some configuration data of a database. That data doesn’t change usually, but the application, in each request, must connect, execute the correct instructions to read the data, pick it up from the network, etc. Imagine also that the database is very busy or the connection is slow. What would happen? We would have a slow application because it is reading continuously data that hardly changes.

A solution to that problem could be using a cache, but how do you implement it? In that article, I explain how to use a basic cache in Spring Boot.

A Little Theory

The cache is replicated over functions, where for the same entry value, we are waiting for the same return value. That’s why we always have at least one parameter for entry and exit.

A typical example will be this:

@Cacheable(cacheNames="headers")
public int cachedFunction(int value){
..... complicated and difficult calculations ....
  return N;
}

And now, let’s suppose we have the next code for calling that function:

int value=cachedFunction(1);
int otherValue=cachedFunction(2);
int thirdValue=cachedFunction(1);

When executing the program, in the first line, Spring will execute the function and save the result that returns. In the second line, if it doesn’t know the value it must return for the input “2.” Nevertheless, in the third line, Spring will detect that a function tagged as @Cacheable   with the name “headers” was already called with the value “1.” It won’t execute the function, it will only return the value that in the first call it saved.

The cache’s name is important because, among other things, it permits us to have different independent caches, which we could clean to instruct Spring Boot to execute the functions again.

So, the idea is that in each call to a function tagged as @Cacheable it will save the return values for each call in an internal table, in such a way that if it already has a return value for one entry, it doesn’t call to the function.

The Practice

And now, let’s get to the practice.

An example project can be found here.

First, we must include the following dependency in our project.

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Now, we can use the tags that will allow us to use Cache  in our application.

The first tag set is  @EnableCaching. With this label, we tell Spring that it must prepare the support to use Cache. If we do not put it, it will simply not use Cache, regardless of whether we then mark the functions with cache tags.

@SpringBootApplication
@EnableCaching
public class CacheExampleApplication {
    public static void main(String[] args) {
          SpringApplication.run(CacheExampleApplication.class, args);
    }
}

In this example, we read the data of a database using REST requests.

Data  in the CacheDataImpl.java class which is in the package com.profesorp.cacheexample.impl

The function that reads the data is the following:

@Cacheable(cacheNames="headers", condition="#id > 1")
public DtoResponse getDataCache(int id) {         
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
    }                              
    DtoResponse requestResponse=new DtoResponse();                     
    Optional<Invoiceheader> invoice=invoiceHeaderRepository.findById(id);
    .....MORE CODE WITHOUT IMPORTANCE ...
}

As can be seen, we have the tag  @Cacheable(cacheNames="headers", condition="#id > 1") 

With this, we told Spring two things:

  1. We want to cache the result of this function.
  2. We put it as a condition that it must store the results in cache if the input is greater than one.

Later, in the function flushCache we put the tag @CacheEvict that cleans the indicated cache. Also, in this case, we tell it to delete all the entries that it has in cache.

@CacheEvict(cacheNames="headers", allEntries=true)
public void flushCache() { }

In the function update we update the database and with the label @CachePut, we inform Spring that it updates the data for the existing value in dtoRequest.id.

Of course, this function must return an object equal to the function labeled with the tag @Cacheable , and we must indicate the input value on which we want to update the data

Running

To understand the application better, we will execute it and give it a request .

The application at the beginning has four invoices in the invoiceHeader table. You can see how it fills the table in the data.sql file

Let’s run the get function of the PrincipalController class. For this we write this:

> curl -s http://localhost:8080/2

The application will return the following:

{"interval":507,"httpStatus":"OK","invoiceHeader":{"id":2,"active":"N","yearFiscal":2019,"numberInvoice":2,"customerId":2}}

The field interval is the time in milliseconds that has takes the application making the request. As can be seen, it has taken more than half a second, because in the getDataCachefunction of CacheDataImpl.java we have a sleep 500instruction.

Now, we execute the call again:

> curl -s http://localhost:8080/2
{"interval":1,"httpStatus":"OK","invoiceHeader":{"id":2,"activo":"N","yearFiscal":2019,"numberInvoice":2,"customerId":2}}

Now the time the call has taken is 1, because Spring hasn’t executed the code of the function, and it has simply returned the value that it had cached.

However, if we request the id as 1, we have indicated that you should not cache this value, always execute the function and therefore we will have a time exceeding 500 milliseconds:

>curl -s http://localhost:8080/1
{"interval":503,"httpStatus":"OK","invoiceHeader":{"id":1,"activo":"S","yearFiscal":2019,"numberInvoice":1,"customerId":1}}
>curl -s http://localhost:8080/1
{"interval":502,"httpStatus":"OK","invoiceHeader":{"id":1,"activo":"S","yearFiscal":2019,"numberInvoice":1,"customerId":1}}
>curl -s http://localhost:8080/1
{"interval":503,"httpStatus":"OK","invoiceHeader":{"id":1,"activo":"S","yearFiscal":2019,"numberInvoice":1,"customerId":1}}

If we call to the flushcache function, we’ll clean the cache and therefore, the next call to the function will execute the code in it.

> curl -s http://localhost:8080/flushcache
Cache Flushed!
> curl -s http://localhost:8080/2
{"interval":508,"httpStatus":"OK","invoiceHeader":{"id":2,"activo":"N","yearFiscal":2019,"numberInvoice":2,"customerId":2}}
> curl -s http://localhost:8080/2
{"interval":0,"httpStatus":"OK","invoiceHeader":{"id":2,"activo":"N","yearFiscal":2019,"numberInvoice":2,"customerId":2}}

Finally, we will see as if we change the value of the field activo to N, since the function that makes the change is labeled with @CacheEvict, it will update the value of the cache, but the getDataCache function won’t execute in the next call.

> curl -X PUT   http://localhost:8080/   -H "Content-Type: application/json"   -d "{\"id\": 2, \"active\": \"N\"}"
>curl -s http://localhost:8080/2
{"interval":0,"httpStatus":"OK","invoiceHeader":{"id":2,"activo":"N","yearFiscal":2019,"numberInvoice":2,"customerId":2}}

Conclusions

Spring without any difficulty allows us to cache the results of the functions. However, you have to take into account that cache is very basic and it is realized in memory. Spring Boot permits us to use external libraries that will allow us to save the data in disc or database.

In the documentation, you can find the different implementations of cache that Spring Boot supports, one of which is EhCache with which you will can different kinds of backend for the data, as well as specify validity times for the data, and more.

Spring Framework Basics: What Is Inversion of Control?

Developers starting with the Spring Framework often get confused with the terminology, specifically dependencies, dependency injection, and Inversion of Control. In this article, we introduce you to the concept of Inversion of Control.

What You Will Learn

  • What is Inversion of Control?
  • What are some examples of Inversion of Control?
  • How does the Spring Framework implement Inversion of Control?
  • Why is Inversion of Control important and what are its advantages?

What Is Inversion of Control?

Approach-1

Have a look at the following implementation of ComplexAlgorithmImpl:

public class ComplexAlgorithmImpl {
BubbleSortAlgorithm bubbleSortAlgorithm = new BubbleSortAlgorithm();
//...
}

One of the numerous things that ComplexAlgorithmImpl does is sorting. It creates an instance of BubbleSortAlgorithm directly within its code.

Approach-2

Now, look at this implementation for a change:

public interface SortAlgorithm {
public int[] sort(int[] numbers);
}

@Component
public class ComplexAlgorithmImpl {
@AutoWired
private SortAlgorithm sortAlgorithm;
//...
}

ComplexAlgorithmImpl here makes use of the SortAlgorithm interface. It also provides a constructor or a setter method where you can set the SortAlgorithminstance into it. The user tells ComplexAlgorithmImpl, which sort algorithm to make use of.

Comparing Approach-1 and Approach-2

Approach-1

  • ComplexAlgorithmImpl can only use BubbleSortAlgorithm; it is tightly coupled.
  • If we need to change ComplexAlgorithmImpl to use quicksort, the relevant code needs to be changed entirely.
  • The control over the BubbleSortAlgorithm dependency is with the ComplexAlgorithmImpl class.

Approach-2

  • ComplexAlgorithmImpl is open to using any implementation of SortAlgorithm, it is loosely coupled.
  • We only need to change the parameter we pass to the constructor or setter of ComplexAlgorithmImpl.
  • The control over the SortAlgorithm dependency is with the user of ComplexAlgorithmImpl.

Inversion Of Control At Play!

In Approach-1, ComplexAlgorithmImpl is tied to a specific sort algorithm.

In Approach-2, it says: give me any sort algorithm and I will work with it.

This is Inversion of Control.

Instead of creating its own dependencies, a class declares its dependencies. The control now shifts from the class to the user of the class to provide the dependency.

Why Is Inversion of Control Important?

Once you write code with Inversion of Control, you can use frameworks like Spring to complete dependency injection and wire up beans and dependencies.

Advantages of Inversion Of Control

  • Inversion of Control makes your code loosely coupled
  • Inversion of Control also makes it easy for the programmer to write effective unit tests

Lastly, be sure to check out the video below on IoC:

image info

Summary

In this article, we talked about Inversion of Control. Instead of a class creating an instance of its own dependency, it leaves it to the user of the class to pass it in and makes code loosely coupled.

Hope you learned something! Let us know what you think in comments below.

50+ Java Interview Questions for Programmers

Hello, guys! Recently, I have been sharing a lot of Java Interview questions and discussion individually, and many of my readers requested to bring them together so that they can have them in the same page and prepare better and this post is the result of that.

This article contains more than 50 Java Interview questions covering all important topics like core Java fundamentals, Java Collection FrameworkJava Multithreading and ConcurrencyJava IOJDBCJVM InternalsCoding ProblemsObject-Oriented programming, etc.

The questions are also picked up from various interviews and they are, by no means, very difficult, and you might have seen them already in your telephonic or face-to-face round of interview.

The questions are also very good to revise important topics like multithreading and collections as I have also shared some useful resources for further learning and improvement like The Complete Java MasterClass to brush up and fill gaps in your Java skills.

So what are we waiting for here is the list of some of the frequently asked Java questions from interviews from both beginner and experienced Java developer of 2 to 5 years experience:

Java Interview Questions and Answers

1)  How Java achieves platform independence? (answer)
hint: bytecode and Java Virtual Machine

2)  What is ClassLoader in Java? (answer)
hint: part of JVM that loads bytecodes for classes. You can write your own.

3)  Write a Java program to check if a number is Even or Odd? (answer)
hint: you can use bitwise operator, e.g. bitwise AND &, remember, even the number has zero at the end in binary format and an odd number has 1 in the end.

4)  Difference between ArrayList and HashSet in Java? (answer)
hint: all differences between List and Set are applicable here, e.g. ordering, duplicates, random search, etc.

5)  What is double checked locking in Singleton? (answer)
hint: two-time check whether instances is initialized or not, first without locking and second with locking.

6)  How do you create thread-safe Singleton in Java? (answer)
hint: many ways, e.g. using Enum or by using double-checked locking pattern or using a nested static class.

7)  When to use volatile variable in Java? (answer)
hint: when you need to instruct the JVM that a variable can be modified by multiple threads and give hint to JVM that does not cache its value.

8)  When to use a transient variable in Java? (answer)
hint: when you want to make a variable non-serializable in a class, which implements the Serializable interface. In other words, you can use it for a variable whose value you don’t want to save. See The Complete Java MasterClass to learn about transient variables in Java.

9)  Difference between the transient and volatile variable in Java? (answer)
hint: totally different, one used in the context of serialization while the other is used in concurrency.

10) Difference between Serializable and Externalizable in Java? (answer)
hint: Externalizable gives you more control over the Serialization process.

11) Can we override the private method in Java? (answer)
hint: No, because it’s not visible in the subclass, a primary requirement for overriding a method in Java.

12) Difference between Hashtable and HashMap in Java? (answer)

hint: several but most important is Hashtable, which is synchronized, while HashMap is not. It’s also legacy and slow as compared to HashMap.

13) Difference between Listand Set in Java? (answer)
hint: List is ordered and allows duplicate. Set is unordered and doesn’t allow duplicate elements.

14) Difference between ArrayList and Vector in Java (answer)
hint: Many, but most important is that ArrayList is non-synchronized and fast while Vector is synchronized and slow. It’s also legacy class like Hashtable.

15) Difference between Hashtable and ConcurrentHashMap in Java? (answer)
hint: more scalable

16) How does ConcurrentHashMap achieve scalability? (answer)
hint: by dividing the map into segments and only locking during the write operation.

17) Which two methods you will override for an Object to be used as Key in HashMap? (answer)
hint: equals and hashcode

18) Difference between wait and sleep in Java? (answer)
hint: The wait() method releases the lock or monitor, while sleep doesn’t.

19) Difference between notify and notifyAll in Java? (answer)
hint: notify notifies one random thread is waiting for that lock while notifyAll inform to all threads waiting for a monitor. If you are certain that only one thread is waiting then use notify, or else notifyAll is better. See Threading Essentials Mini-Course by Java Champion Heinz Kabutz to learn more about threading basics.

20) Why you override hashcode, along with equals() in Java? (answer)
hint: to be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes, e.g. HashMap or ArrayList.

21) What is the load factor of HashMap means? (answer)
hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means HashMap resize itself if it’s 75 percent full.

22) Difference between ArrayList and LinkedList in Java? (answer)
hint: same as an array and linked list, one allows random search while other doesn’t. Insertion and deletion easy on the linked list but a search is easy on an array. See Java Fundamentals: Collections Richard Warburton course on Pluralsight to learn more about essential Collection data structure in Java.

23) Difference between CountDownLatch and CyclicBarrier in Java? (answer)
hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse CountDownLatch   after the count reaches to zero.

24) When do you use Runnable vs Thread in Java? (answer)
hint: always

25) What is the meaning of Enum being type-safe in Java? (answer)
hint: It means you cannot assign an instance of different Enum type to an Enum variable. e.g. if you have a variable like DayOfWeek day then you cannot assign it value from DayOfMonth enum.

26) How does Autoboxing of Integer work in Java? (answer)
hint: using valueOf() method

27) Difference between PATH and Classpath in Java? (answer)
hint: PATH is used by the operating system while Classpath is used by JVM to locate Java binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn more about PATHClasspath, and other Java environment variable.

28) Difference between method overloading and overriding in Java? (answer)
hint: Overriding happens at subclass while overloading happens in the same class. Also, overriding is a runtime activity while overloading is resolved at compile time.

29) How do you prevent a class from being sub-classed in Java? (answer)
hint: just make its constructor private

30) How do you restrict your class from being used by your client? (answer)
hint:  make the constructor private or throw an exception from the constructor

31) Difference between StringBuilder and StringBuffer in Java? (answer)
hint: StringBuilder is not synchronized while StringBuffer is synchronized.

32) Difference between Polymorphism and Inheritance in Java? (answer)
hint: Inheritance allows code reuse and builds the relationship between class, which is required by Polymorphism, which provides dynamic behavior. See Java Fundamentals: Object-Oriented Design to learn more about OOP features.

33) Can we override static method in Java? (answer)
hint: No, because overriding resolves at runtime while static method call is resolved at compile time.

34) Can we access the private method in Java? (answer)
hint: yes, in the same class but not outside the class

35) Difference between interface and abstract class in Java? (answer)
hint: from Java 8, the difference is blurred. However, a Java class can still implement multiple interfaces but can only extend one class.

36) Difference between DOM and SAX parser in Java? (answer)
hint: DOM loads whole XML File in memory while SAX doesn’t. It is an event-based parser and can be used to parse a large file, but DOM is fast and should be preferred for small files.

37) Difference between throw and throws keyword in Java? (answer)
hint: throws declare what exception a method can throw in case of error but throw keyword actually throws an exception. See Java Fundamentals: Exception Handling to learn more about Exception handling in Java.

38) Difference between fail-safe and fail-fast iterators in Java? (answer)
hint: fail-safe doesn’t throw ConcurrentModificationException while fail-fast does whenever they detect an outside change on the underlying collection while iterating over it.

39) Difference between Iterator and Enumeration in Java? (answer)
hint: Iterator also gives you the ability to remove an element while iterating while Enumeration doesn’t allow that.

40) What is IdentityHashMap in Java? (answer)
hint: A Map, which uses  the == equality operator to check equality instead of the equals() method.

41) What is String pool in Java? (answer)
hint: A pool of String literals. Remember it’s moved to heap from perm gen space in JDK 7.

42) Can a Serializable class contain a non-serializable field in Java? (answer)

hint: Yes, but you need to make it either static or transient.

43) Difference between this and super in Java? (answer)
hint: this refers to the current instance while super refers to an instance of the superclass.

44) Difference between Comparator and Comparable in Java? (answer)
hint: Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order for String. See The Complete Java MasterClass to learn more about sorting in Java.

45) Difference between java.util.Date and java.sql.Date in Java? (answer)
hint: former contains both date and time while later contains only date part.

46) Why wait and notify method are declared in Object class in Java? (answer)
hint: because they require lock which is only available to an object.

47) Why Java doesn’t support multiple inheritances? (answer)
hint: It doesn’t support because of bad experience with C++, but with Java 8, it does in some sense — only multiple inheritances of Type are not supported in Java now.

48) Difference between checked and unchecked Exception in Java? (answer)
hint: In case of checked, you must handle exception using catch block, while in case of unchecked, it’s up to you; compile will not bother you.

49) Difference between Error and Exception in Java? (answer)
hint: I am tired of typing please check the answer

50) Difference between race condition and deadlock in Java? (answer)
hint: both are errors that occur in a concurrent application, one occurs because of thread scheduling while others occur because of poor coding.

Additional Resources

Lifecycle of a Request-Response Process for a Spring REST API

Developing a REST API or microservice using the Spring Boot framework accelerates the development process, and allows API developers to only focus on writing the core business logic and not worry about all the underlying configurations and setup. This article describes the steps involved in the lifecycle of a request process and how the request is mapped to the appropriate controller method and how a response is returned to the client.

In order to create a REST API to serve a client with a list of users, the tasks involved are

  • Create a class with the @RestController annotation. Due to the annotation, this class will be auto-detected through classpath scanning and the methods annotated with @RequestMapping annotation will be exposed as HTTP endpoints. When an incoming request matches the requirements specified by the @RequestMapping annotation, the method will execute to serve the request.

For our example of a users API, the controller class will look like this:

@RestController
@RequestMapping("/users")
public class UserController {
                @Autowired
                UserService userService

                @RequestMapping(method = RequestMethod.GET)
                public List<UserDTO> findAllUsers() {
                                return userService.findAllUsers();
                }
}
  • Create a class for business logic.
  • Create a class to fetch data from the user table.

From a developer’s perspective, the flow to fetch the list of users from the database can be viewed as below:Image titleHowever, with Spring doing a lot of work for us behind the scenes, the lifecycle of the entire process for making an HTTP request to a resource to serving the response back to the client in either XML/JSON format involves many more steps.

This article describes the entire request to response lifecycle with steps which are managed by Spring.

When a user makes a request for a resource, for example:

Request: http://localhost:8080/users 

Accept: application/json 

This incoming request is handled by the DispatcherServlet, which is auto-configured by Spring Boot. While creating a project through the Spring Boot framework, and when we mention the Spring Boot Starter Web as a dependency in pom.xml, Spring Boot’s auto-configuration feature configures dispatcherServlet, a default error page, and other dependent jar files.

When a Spring boot application is run, the log will have a message like this:

[ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: ‘dispatcherServlet’ to [/]

DispatcherServlet is the front controller and all incoming request goes through this single servlet.

The process from a request to response is shown in the below flow chart:

Image title

The blocks in the green are the ones which are implemented by developers.

In our request for /users resources, the activities below are performed in each step:

  1. In Step 1, the dispatcher servlet will intercept the request for the resource /users.
  2. In Step 2, the servlet determines the handler for the request (a good link on this topic).
  3. In Step 3, Spring checks which controller method matches the incoming lookup path of the “/users” request. Spring maintains a list of all mapping registries fetched from the @RequestMapping of the controller class and iterates the list to look for the matching method in the controller class implemented by the developer.
  4. In Step 4, after determining the right method it executes the controller method.
  5. Step 5 returns an ArrayList of users.
  6. The response type accepted by the client can be either JSON or XML. Therefore, Step 6 does the job of marshaling the Java object to the response type requested by the client. Spring takes the ArrayList of users and uses the message converter method to marshal it to the type requested by the client. If the converted message is not available, then the client will get a 406 error. In the case of users, as the requested type is JSON, thus a JSON object for users is returned as a response.

Conclusion

Understanding the lifecycle of the request and response process and other classes involved helps one to understand the issues better and troubleshoot it more easily. To check the process lifecycle, open the Eclipse Open Type DispatcherServlet class and add a breakpoint at the doDispatch method.