dineshonjava

Difference between Abstraction vs Encapsulation in Java

In very short
Encapsulation:-- Information hiding.
Abstraction:-- Implementation hiding.
Abstraction and Encapsulation both are OOP concepts of any object oriented programming languages which allow us to wrap real world things into classes and objects for using in the programming of application. Both Abstraction and Encapsulation in OOPs using hiding information to the world, so these are very confusing to understand the differnce between each other for beginners. So in very simple word I am telling you about Abstraction, it is nothing but it is one of the OOP concept which focuses on the process of hiding the unwanted details and exposing only the essential features of a particular object or concept, and Encapsulation is also one of the OOP concepts which also hides data from outside world but there are key differences between them to way of hiding data outside of world.

So what is different way of hiding data, that is, Abstraction hides complexity by giving you a more abstract picture of a complex system, For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other, while Encapsulation hides internal working so that you can change it later, For example, all implementations and declaration related to the car wrap in the single unit called class i.e. Car class. In short we can say, Abstraction hides details at the design level, while Encapsulation hides details at the implementation level.


Suppose in above example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. When we first describe an object, you talk in more abstract term e.g. a Car has Engine, Gearbox, Steering objects but you don't tell how to start engine, how to work Gearbox etc, Car will move, whether it will move by using tires or it will fly. It just moves. This is called Abstraction. We are talking about a most essential thing, which is moving, having engine, have gearbox etc rather than focusing on details of how to moving and starting engine.

In the programming, it is good practice to define different levels of Abstraction in the application and the classes should interact with other classes with the same level of abstraction or higher level of abstraction. As we increase the level of Abstraction, things start getting simpler and simpler because we leave out details.

In the OOP concept, Encapsulation is all about implementation. It wraps implementation and data into single unit, its purpose is to hide internal implementation of objects from outside world so that you can change this implementation later without impacting outside world.

Let's see with example, in HashMap there are two very important method implementations put() and get() method. But developer only need to know hot put and get object to the HashMap instead how to work these implementation of HashMap internally. Because of Encapsulation, you can change the internal implementation of HashMap with ease without impacting clients who are using HashMap.

Advantage of Abstraction:

  1. By using abstraction, we can separate the things that can be grouped to another type.
  2. Frequently changing properties and methods can be grouped to a separate type so that the main type need not under go changes. This adds strength to the OOAD principle -"Code should be open for Extension but closed for Modification".
  3. Simplifies the representation of the domain models.


Advantage of Encapsulation:

  1. Encapsulated Code is more flexible and easy to change with new requirements.
  2. Encapsulation in Java makes unit testing easy.
  3. Encapsulation in Java allows you to control who can access what.
  4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environment.
  5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing are encapsulated in one place.
  6. Encapsulation allows you to change one part of code without affecting other part of code.

Difference between Abstraction vs Encapsulation
Difference between Abstraction vs Encapsulation in Java
  • Abstraction hide the things at design level but Encapsulation hide things at implementation level.
  • Abstraction can be defined as the process of hiding the unwanted details and exposing only the essential features of a particular object or concept, while Encapsulation is a way of wrapping up data and methods into a single unit. Encapsulation puts the data safe from the outside world by binding the data and codes into single unit.
  • Abstraction lets you focus on what the object does instead of how it does, while Encapsulation means hiding the internal details of how an object works. When you keep internal working details private, you can change it later with a better method.
  • Abstraction is supported using interface and abstract class while Encapsulation is supported using access modifiers e.g. public, private and protected.
  • Abstraction means to show What part of functionality while Encapsulation means to hide the How part of the functionality.



Difference between a Checked and Unchecked exception?

Checked Exception: There are many exceptions in programming which occurs regularly but there are some exceptions in the program will be checked by compiler at compile time, those exceptions are called Checked Exceptions. Suppose some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

Example: Some checked exceptions in java are FileNotFoundException, EndOfFileException etc.

class Main {
    public static void main(String[] args) {
        FileReader file = new FileReader("D:\\temp\\temp.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Do processing with file and close it as below
         
        fileInput.close();
    }
}


The above program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.

class Main {
    public static void main(String[] args) throws IOException{
        FileReader file = new FileReader("D:\\temp\\temp.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Do processing with file and close it as below
         
        fileInput.close();
    }
}


Unchecked Exception: As we told above there are many exceptions in the programming, some occurs regularly are checked and another some exceptions which do not occur regularly in a program, and compiler will not check for those exceptions, these kind of exceptions are called Unchecked Exceptions. Means unchecked are the exceptions that are not checked at compiled time by compiler unlike checked exceptions. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

Example: Some unchecked exceptions in java are ArithmeticException, NullPointerException etc.

class Example{
public static void main(String[] args){
System.out.println(10/0); //Arithmetic Exception
}
}


The above program should throw "Arithmetic Exception" as division with "0" is not allowed, but it compiles fine, only it throws ArithmeticException when run. The compiler allows it to compile, because ArithmeticException is an unchecked exception.

Difference between a Checked and Unchecked exception


Microservices Interview Questions Answers

In this article, I have collected top 10 spring boot microservices interview questions and their answers frequently asked by interviewers. If you want to learn more about microservice architecture with spring boot, you could follow my previous article create microservices application using spring boot.


1. What is Spring Boot?
Spring Boot is a way to ease to create stand-alone application with minimal or zero configurations. It is approach to develop spring based application with very less configuration. It provides defaults for code and annotation configuration to quick start new spring projects within no time. It leverages existing spring projects as well as Third party projects to develop production ready applications. It provides a set of Starter Pom’s or gradle build files which one can use to add required dependencies and also facilitate auto configuration.

Spring Boot automatically configures required classes depending on the libraries on its classpath. Suppose your application want to interact with DB, if there are Spring Data libraries on class path then it automatically sets up connection to DB along with the Data Source class. For more detail about Spring Boot.

2. What is a microservices architecture?
Microservices architecture allows to avoid monolith application for large system. It provide loose coupling between collaborating processes which running independently in different environments with tight cohesion. For more detail.

3. What are the advantages and disadvantages of microservices?
Microservices Advantages

  • Smaller code base is easy to maintain.
  • Easy to scale as individual component.
  • Technology diversity i.e. we can mix libraries, databases, frameworks etc.
  • Fault isolation i.e. a process failure should not bring whole system down.
  • Better support for smaller and parallel team.
  • Independent deployment
  • Deployment time reduce


Microservices Disadvantages

  • Difficult to achieve strong consistency across services
  • ACID transactions do not span multiple processes.
  • Distributed System so hard to debug and trace the issues
  • Greater need for end to end testing
  • Required cultural changes in across teams like Dev and Ops working together even in same team.


4. What is Spring Cloud?

  • It is building blocks for Cloud and Microservices
  • It provides microservices infrastructure like provide use services such as Service Discovery, Configuration server and Monitoring.
  • It provides several other open source projects like Netflix OSS.
  • It provides PaaS like Cloud Foundry, AWS and Heroku.
  • It uses Spring Boot style starters
  • There are many use-cases supported by Spring Cloud like Cloud Integration, Dynamic Reconfiguration, Service Discovery, Security,Client side Load Balancing etc. But in this post we concentrate on following microservices support
  • Service Discovery (How do services find each other?)
  • Client-side Load Balancing (How do we decide which service instance to use?)


5. Spring Cloud annotations and configuration?

  • @EnableEurekaServer annotation allows us to register microservices to the spring cloud.
  • @EnableDiscoveryClient annotation also allows us to query Discovery server to find miroservices.
  • Spring provide smart RestTemplate for service discovery and load balancing by using @LoadBalanced annotation with RestTemplate instance.


6. What Netflix projects did we use?
Eureka created by Netflix, it is the Netflix Service Discovery Server and Client. Netflix Ribbon, it provide several algorithm for Client-Side Load Balancing. Spring provide smart RestTemplate for service discovery and load balancing by using @LoadBalanced annotation with RestTemplate instance.

7. How do you setup Service Discovery?
Spring Cloud support several ways to implement service discovery but for this I am going to use Eureka created by Netflix. Spring Cloud provide several annotation to make it use easy and hiding lots of complexity. For more detail click here.

8. How do you access a RESTful microservice?

  • Load Balanced RestTemplate
  • If there are multiple RestTemplate you get the right one.
  • It can used to access multiple microservices


9. What is Eureka?
Eureka is the Netflix Service Discovery Server and Client. Eureka Server is using Spring Cloud.

Registering with Eureka

When a client registers with Eureka, it provides meta-data about itself such as host and port, health indicator URL, home page etc. Eureka receives heartbeat messages from each instance belonging to a service. If the heartbeat fails over a configurable timetable, the instance is normally removed from the registry.

Example eureka client:

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

For full example of microservices with spring boot click here.


Spring Boot Related Topics
  1. Spring Boot Interview Questions and Answers
  2. Introduction to Spring Boot
  3. Essentials and Key Components of Spring Boot
  4. Spring Boot CLI Installation and Hello World Example
  5. Spring Boot Initializr Web Interface
  6. Spring Boot Initializr With IDEs
  7. Spring Boot Initializr With Spring Boot CLI
  8. Installing Spring Boot
  9. Developing your first Spring Boot application
  10. External Configurations for Spring Boot Applications
  11. Logging Configuration in Spring Boot
  12. Spring Boot and Spring MVC
  13. Working with SQL Databases and Spring Boot
  14. MySQL Configurations
  15. Spring Data JPA using Spring Boot Application
  16. Spring Boot with NoSQL technologies
  17. Spring Cache Tutorial
  18. Spring Security Tutorial with Spring Boot
  19. Spring Boot and MongoDB in REST Application
  20. Complete Guide for Spring Boot Actuator
  21. Microservices with Spring Boot


Spring Boot Interview Questions and Answers

In this article, I have collected best top 20 most frequently asked spring boot interview questions and answers with explanation. You can find more detail about Spring Boot in my previous Spring Boot tutorial and also microservices architecture with Spring Boot.

Spring Boot Interview Questions
  1. What is Spring Boot?
  2. What are the advantages of using Spring Boot?
  3. What are the disadvantages of using Spring Boot?
  4. Why is it "opinionated"?
  5. How does it work? How does it know what to configure?
  6. How are properties defined? Where?
  7. What is the difference between an embedded container and a WAR?
  8. What embedded containers does Spring Boot support?
  9. What does @EnableAutoConfiguration do? What about @SpringBootApplication?
  10. What is a Spring Boot starter POM? Why is it useful?
  11. Spring Boot supports both Java properties and YML files. Would you recognize and understand them if you saw them?
  12. Can you control logging with Spring Boot? How?
  13. How to reload my changes on Spring Boot without having to restart server?
  14. What is Actuator in Spring Boot?
  15. How to run Spring boot application to custom port?
  16. How to implement security for Spring boot application?
  17. What is the configuration file name used by Spring Boot?
  18. How to implement Spring web using Spring boot?
  19. How to configure database using Spring boot?
  20. What is YAML?

Spring Boot Interview Questions and Answers

1. What is Spring Boot?
First of all Spring Boot is not a framework, it is a way to ease to create stand-alone application with minimal or zero configurations. It is approach to develop spring based application with very less configuration. It provides defaults for code and annotation configuration to quick start new spring projects within no time. It leverages existing spring projects as well as Third party projects to develop production ready applications. It provides a set of Starter Pom’s or gradle build files which one can use to add required dependencies and also facilitate auto configuration.

Spring Boot automatically configures required classes depending on the libraries on its classpath. Suppose your application want to interact with DB, if there are Spring Data libraries on class path then it automatically sets up connection to DB along with the Data Source class.

2. What are the advantages of using Spring Boot?

  • It is very easy to develop Spring Based applications with Java or Groovy.
  • It reduces lots of development time and increases productivity.
  • It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
  • It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
  • It follows "Opinionated Defaults Configuration" Approach to reduce Developer effort
  • It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
  • It provides CLI (Command Line Interface) tool to develop and test Spring Boot (Java or Groovy) Applications from command prompt very easily and quickly.
  • It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and Gradle
  • It provides lots of plugins to work with embedded and in-memory Databases very easily.

3. What are the disadvantages of using Spring Boot?
It is very tough and time consuming process to convert existing or legacy Spring Framework projects into Spring Boot Applications. It is applicable only for brand new/Greenfield Spring Projects.

4. Why is it "opinionated"?
It follows "Opinionated Defaults Configuration" Approach to reduce Developer effort. Due to opinionated view of spring boot, what is required to get started but also we can get out if not suitable for application.
• Spring Boot uses sensible defaults, “opinions”, mostly based on the classpath contents.
• For example
– Sets up a JPA Entity Manager Factory if a JPA implementation is on the classpath.
– Creates a default Spring MVC setup, if Spring MVC is on the classpath.
• Everything can be overridden easily
– But most of the time not needed

5. How does it work? How does it know what to configure?
• Auto-configuration works by analyzing the classpath
– If you forget a dependency, Spring Boot can't configure it
– A dependency management tool is recommended
– Spring Boot parent and starters make it much easier
• Spring Boot works with Maven, Gradle, Ant/Ivy
– Our content here will show Maven

6. How are properties defined? Where?
In spring boot, we have to define properties in the application.properties file exists in classpath of application as follow.
Example: configure default DataSource bean
database.host=localhost
database.user=admin

7. What is the difference between an embedded container and a WAR?
There is no force to go container less
– Embedded container is just one feature of Spring Boot
• Traditional WAR also benefits a lot from Spring Boot
– Automatic Spring MVC setup, including DispatcherServlet
– Sensible defaults based on the classpath content
– Embedded container can be used during development

8. What embedded containers does Spring Boot support?
Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers.
By default the embedded server will listen for HTTP requests on port 8080.

9. What does @EnableAutoConfiguration do? What about @SpringBootApplication?
@EnableAutoConfiguration annotation on a Spring Java configuration class
– Causes Spring Boot to automatically create beans it thinks you need
– Usually based on classpath contents, can easily override

@Configuration
@EnableAutoConfiguration
public class MyAppConfig {
public static void main(String[] args) {
SpringApplication.run(MyAppConfig.class, args);
}
}
@SpringBootApplication was available from Spring Boot 1.2
It is very common to use @EnableAutoConfiguration, @Configuration, and @ComponentScan together.

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MyAppConfig {
...
}

With @SpringBootApplication annotation
@SpringBootApplication
public class MyAppConfig {
...
}

10. What is a Spring Boot starter POM? Why is it useful?
Starters are a set of convenient dependency descriptors that you can include in your application. The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.

The starter POMs are convenient dependency descriptors that can be added to your application’s Maven. In simple words, if you are developing a project that uses Spring Batch for batch processing, you just have to include spring-boot-starter-batch that will import all the required dependencies for the Spring Batch application. This reduces the burden of searching and configuring all the dependencies required for a framework.

11. Spring Boot supports both Java properties and YML files. Would you recognize and understand them if you saw them?
spring boot application java property file name is application.properties
spring boot application YML file name is application.yml

12. Can you control logging with Spring Boot? How?
Yes, we can control logging with spring boot.

Customizing default Configuration for Logging:
By adding logback.xml file to the application we can override the default logging configuration providing by the Spring Boot. This file place in the classpath (src/main/resources) of the application for Spring Boot to pick the custom configuration.

Spring Boot can control the logging level
– Just set it in application.properties
• Works with most logging frameworks
– Java Util Logging, Logback, Log4J, Log4J2
logging.level.org.springframework=DEBUG
logging.level.com.acme.your.code=INFO

13. How to reload my changes on Spring Boot without having to restart server?
Include following maven dependency in the application.

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>springloaded</artifactId>
 <version>1.2.6.RELEASE</version>
</dependency>

Automatic restart
Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

This can be achieved using DEV Tools. With this dependency any changes you save, the embedded tomcat will restart. Spring Boot has a Developer tools (DevTools) module which helps to improve the productivity of developers. One of the key challenge for the Java developers is to auto deploy the file changes to server and auto restart the server. Developers can reload changes on Spring Boot without having to restart my server. This will eliminates the need for manually deploying the changes every time. Spring Boot doesn’t have this feature when it has released it’s first version. This was a most requested features for the developers. The module DevTools does exactly what is needed for the developers. This module will be disabled in the production environment.

14. What is Actuator in Spring Boot?
pring Boot Actuator is a sub-project of Spring Boot. It adds several production grade services to your application with little effort on your part. There are also has many features added to your application out-of-the-box for managing the service in a production (or other) environment. They’re mainly used to expose different types of information about the running application – health, metrics, info, dump, env etc.

15. How to run Spring boot application to custom port ?
In application.properties, add following property.
server.port = 8181

16. How to implement security for Spring boot application ?
Add spring security starter to the boot application
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
  </dependency>

17. What is the configuration file name used by Spring Boot?
The configuration file used in spring boot projects is application.properties. This file is very important where we would over write all the default configurations. Normally we have to keep this file under the resources folder of the project.

18. How to implement Spring web using Spring boot?
Web Application Convenience 
• Boot automatically configures
– A DispatcherServlet & ContextLoaderListener
– Spring MVC using same defaults as @EnableWebMvc
• Plus many useful extra features:
– Static resources served from classpath
• /static, /public, /resources or /META-INF/resources
– Templates served from /templates
• If Velocity, Freemarker, Thymeleaf, or Groovy on classpath
– Provides default /error mapping
• Easily overridden
– Default MessageSource for I18N

19. How to configure datasource using Spring boot?
• Use either spring-boot-starter-jdbc or spring-boot-starterdata-jpa and include a JDBC driver on classpath
• Declare properties
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
– Spring Boot will create a DataSource with properties set
– Will even use a connection pool if the library is found on the classpath!

20. What is YAML?
Yaml Ain't a Markup Language
– Recursive acronym
• Created in 2001
• Alternative to .properties files
– Allows hierarchical configuration
• Java parser for YAML is called SnakeYAML
– Must be in the classpath
– Provided by spring-boot-starters

YAML for Properties
• Spring Boot support YAML for Properties
– An alternative to properties files
application.properties
database.host = localhost
database.user = admin
application.yml
database:
    host: localhost
    user: admin
• YAML is convenient for hierarchical configuration data
– Spring Boot properties are organized in groups
– Examples: server, database, etc


Difference between @Controller vs @RestController in Spring MVC

The key difference between a traditional Spring MVC @Controller and the RESTful web service @RestController is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML by registered HttpMessageConverters.

Traditional Spring MVC Workflow
The following image describe a traditional Spring MVC Request workflow:
Spring MVC traditional workflow
@ImageSource-https://www.genuitec.com

  • Step 1: The browser or client sends a request to the web application.
  • Step 2: The request lands to the dispachter servlet and consult with handler mapping.
  • Step 3: The Handler mappings defined in the application context file, this has information about which is controller need to be invoked.
  • Step 4: The controller will be invoked and it can request the model for some information using DAOs and Services.
  • Step 5: After Requests are processed by the Controller and the response is returned to the DispatcherServlet with logical view name
  • Step 6: Then return to the view resolver prepared the view based on your configuration decide the which configuration (JSP, Velocity, PDF etc.) to be invoked.

For Example:
@Controller
public class AccountController {
  @RequestMapping(value="/account", method=RequestMethod.GET)
  public ModelAndView get(Long accountId) {
    //Process model object
    return new ModelAndView("account-detail", model) ;
  }
}

Spring MVC REST Workflow
The following image describe a Spring MVC REST workflow:

Spring REST workflow
@ImageSource-https://www.genuitec.com

  • Step 1: The client sends a request to a web service in URI form.
  • Step 2: The request lands to the dispachter servlet and consult with handler mapping.
  • Step 3: The Handler mappings defined in the application context file, this has information about which is controller need to be invoked.
  • Step 4: The controller will be invoked and process model.
  • Step 5: Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.

In Traditional Spring MVC Workflow, notice that controller return the ModelAndView object with logical view name to dispactcher servlet, it is forwarded to the ViewResolver in step 6. But in the Spring MVC REST Workflow, Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. As of Spring Version 4.0, this process has been more simplified by the @RestController annotation.

For Example:

Using the @ResponseBody Annotation
If any handler method of controller class is annotated with @ResponseBody, Spring converts the return value of this method and writes it to the http response automatically.

What is Behind the @ResponseBody
There is a list of HttpMessageConverters registered in the background when we enable Spring web mvc feature to the web application by using @EnableWebMvc or <mvc:annotation-driven> namespace. HTTPMessageConverter is responsible to convert the request body to a specific class and back to the response body again, depending on a predefined mime type.

Create the following @Controller class:
/**
 * 
 */
package com.doj.restapi.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.doj.restapi.bean.Account;
import com.doj.restapi.service.IAccountService;

/**
 * @author Dinesh.Rajput
 *
 */
@Controller
public class AccountController {
 
 @Autowired
 IAccountService accountService;
 
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public @ResponseBody String home (){
  return "Spring REST Dinesh on Java!!!";
 }
 
 @RequestMapping(value = "/accounts", method = RequestMethod.GET)
 public @ResponseBody List<Account> all (){
  return accountService.list();
 }
 
 @RequestMapping(value = "/account", method = RequestMethod.POST)
 public @ResponseBody Account create (@RequestBody Account account){
  return accountService.create(account);
 }
 
 @RequestMapping(value = "/account/{accountId}", method = RequestMethod.GET)
 public @ResponseBody Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
 }
 
 @RequestMapping(value = "/account", method = RequestMethod.PUT)
 public @ResponseBody Account update (@RequestBody Account account){
  return accountService.update(account);
 }
 
 @RequestMapping(value = "/account/{accountId}", method = RequestMethod.DELETE)
 public @ResponseBody void delete (@PathVariable Long accountId){
  accountService.delete(accountId);
 }
}

Notice the @ResponseBody added to each of the @RequestMapping methods in the return value.

Using the @RestController Annotation
@RestController annotation is introduced as of Spring 4.0, it is actually combination of @Controller and @ResponseBody. It is a convenience way to use this annotation instead of using @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default.

Spring REST workflow using RestController
@ImageSource-https://www.genuitec.com

Let's use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. As following:

/**
 * 
 */
package com.doj.restapi.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.doj.restapi.bean.Account;
import com.doj.restapi.service.IAccountService;

/**
 * @author Dinesh.Rajput
 *
 */
@RestController
public class AccountController {
 
 @Autowired
 IAccountService accountService;
 
 @GetMapping("/")
 public String home (){
  return "Spring REST Dinesh on Java!!!";
 }
 
 @GetMapping("/accounts")
 public List<Account> all (){
  return accountService.list();
 }
 
 @PostMapping("/account")
 public Account create (@RequestBody Account account){
  return accountService.create(account);
 }
 
 @GetMapping("/account/{accountId}")
 public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
 }
 
 @PutMapping("/account")
 public Account update (@RequestBody Account account){
  return accountService.update(account);
 }
 
 @DeleteMapping("/account/{accountId}")
 public void delete (@PathVariable Long accountId){
  accountService.delete(accountId);
 }
}


As per as above controller file with @RestController annotation, we can see, using this annotation is quite simple and is the preferred method for creating MVC RESTful web services if we are using Spring v4.0 and above.



WebMvcConfigurerAdapter vs WebMvcConfigurationSupport in Spring MVC

In this tutorial, we will discuss about difference between webmvcconfigureradapter vs webmvcconfigurationsupport. These both classes are related to Spring MVC java based configuration. It is actually simplified web configuration with Spring in the web application. Let's see some differences between of these two classes.


WebMvcConfigurerAdapter vs WebMvcConfigurationCupport

WebMvcConfigurationSupport WebMvcConfigurerAdapter
In the Spring MVC framework, this is the main class providing the configuration behind the MVC Java config. This is simple adapter class for customizing some of the default configuration.
We could use the @EnableWebMvc annotation to import the configuration of this class automatically. This is not related to the @EnableWebMvc annotation.
We could extend WebMvcConfigurationSupport class to prevent the default configuration imported by the @EnableWebMvc annotation. We could extend WebMvcConfigurerAdapter class to customize some of the default configuration imported by @EnableWebMvc annotation.
In the java configuration file for spring mvc either we could use @EnableWebMvc annotation or extend WebMvcConfigurationSupport class. If we are extending this class, still required to use @EnableWebMvc annotation, otherwise application will not work.




Spring REST Web Services Interview Questions and Answers

Spring REST Web Services Interview Questions and Answers
In this tutorial, I am putting collection of frequently asked important spring REST web services interview questions with answers. It will be help in the Spring REST related questions in the interview. You could also read my another articles related to Spring interview questions with answers for helping in the Spring related interviews. These articles listed as below.

Let's see the below questions related to Spring REST web services.

Spring REST Service Interview Questions
  1. Define Web Service?
  2. What does REST stand for? and what is RESTful web services?
  3. What is differences between RESTful web services and SOAP web services?
  4. What is a resource?
  5. What are safe REST operations?
  6. What are idempotent operations? Why is idempotency important?
  7. Is REST scalable and/or interoperable?
  8. What are the advantages of the RestTemplate?
  9. Which HTTP methods does REST use?
  10. What is an HttpMessageConverter?
  11. Is REST normally stateless?
  12. What does @RequestMapping do?
  13. Is @Controller a stereotype? Is @RestController a stereotype?
  14. What is the difference between @Controller and @RestController?
  15. When do you need @ResponseBody?
  16. What does @PathVariable do?
  17. What is the HTTP status return code for a successful DELETE statement?
  18. What does CRUD mean?
  19. Is REST secure? What can you do to secure it?
  20. Where do you need @EnableWebMVC?
  21. Name some common http response codes. When do you need @ResponseStatus?
  22. Does REST work with transport layer security (TLS)?
  23. Do you need Spring MVC in your classpath for Spring REST?

1. Define Web Service?
A web service is a kind of software that is accessible on the Internet. It makes use of the XML messaging system and offers an easy to understand, interface for the end users.

2. What does REST stand for? and what is RESTful web services?
REST stand for REpresentational State Transfer, term by Roy Fielding. REST is an architectural style that describes best practices to expose web services over HTTP with Emphasizes scalability. Web services written by apply REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol to a different clients written in different languages. In RESTful web services http methods like GET, PUT, POST and DELETE can can be used to perform CRUD operations. Read more about REST.

3. What is differences between RESTful web services and SOAP web services?
1) REST is more simple and easy to use than SOAP
2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.
3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA's.
4) REST supports different format like text, JSON and XML while SOAP only support XML.
5) REST web services call can be cached to improve performance.

4. What is a resource?
The key abstraction of information in REST is a resource. Any information that can be named can be a resource like Student, Employee etc. REST is resource based API. Expose resources through URIs like http://localhost:8080/api/employees/1111, It is based on Model nouns, not verbs. Resources support limited set of operations – GET, PUT, POST, DELETE in case of HTTP. Example: update an employee use PUT to /employees/1111 and don't POST to /employees/edit?id=1111 and Resources can support multiple representations like HTML, XML, JSON etc. Multiple URIs may refers to same resource as like CRUD operation on employee resource using HTTP verbs. Read More>>>

5. What are safe REST operations?
Safe REST operations are HTTP methods that do not modify resources. For example, using GET or HEAD on a resource URL, should NEVER change the resource. But it is still possible, that safe operations do change things on a server or resource. For example: GET http://localhost:8080/api/employees/1111/delete HTTP/1.1 but it is incorrect, this would actually delete the employee i.e. Safe methods are methods that can be cached, prefetched without any repercussions to the resource.

6. What are idempotent operations? Why is idempotency important?
Idempotent operations are those HTTP methods that can be called repetitively many times without different outcomes. It would not matter if the method is called only once, or many times over. The result should be the same. Again, this only applies to the result, not the resource itself.
Consider the following examples:

a = 4; (is idempotent)
a++; (is not idempotent)

Idempotency is important in building a fault-tolerant API. Suppose a client wants to update a resource through POST. Since POST is not a idempotent method, calling it multiple times can result in wrong updates. What would happen if you sent out the POST request to the server, but you get a timeout. Is the resource actually updated? Does the timeout happened during sending the request to the server, or the response to the client? Can we safely retry again, or do we need to figure out first what has happened with the resource? By using idempotent methods, we do not have to answer this question, but we can safely resend the request until we actually get a response back from the server.

HTTP Method Idempotent Safe
OPTIONS yes yes
GET yes yes
HEAD yes yes
PUT yes no
POST no no
DELETE yes no
PATCH no no

7. Is REST scalable and/or interoperable?
Yes, REST is scalable and interoperable.

8. What is the RestTemplate and It's advantages?
In Spring REST client, The RestTemplate is the core class for client-side access to Spring RESTful web services. It communicates HTTP server using RESTful constraints. It is very similar to other template classes in the Spring like JdbcTemplate and HibernateTemplate etc. In Spring, RestTemplate provides higher level implementation of corresponding HTTP methods such as GET, POST, PUT, DELETE, HEAD etc. It provides the methods to communicate by using these HTTP methods with URI template, URI params, request object and response type as arguments. Read More about RestTemplate.


9. Which HTTP methods does REST use?
RestTemplate provides higher level implementation of corresponding HTTP methods such as GET, POST, PUT, DELETE, HEAD etc.

10. What is an HttpMessageConverter?
HttpMessageConverter is a strategy interface that specifies a converter that can convert from and to HTTP requests and responses. Internally Spring MVC uses it to convert the Http request to an object representation and back. Message converters are used to marshall and unmarshall Java Objects to and from JSON, XML, etc – over HTTP. Read More about HttpMessageConverter in Spring.


11. Is REST normally stateless?
Yes.

12. What does @RequestMapping do?
@RequestMapping can be applied to the controller class as well as methods. This annotation for mapping web requests onto specific handler classes and/or handler methods. Read more about @RequestMapping annotation.


13. Is @Controller a stereotype? Is @RestController a stereotype?
Yes.

14. What is the difference between @Controller and @RestController?
The key difference between a traditional Spring MVC @Controller and the RESTful web service @RestController is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML by registered HttpMessageConverters.

15. When do you need @ResponseBody?
When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.

16. What does @PathVariable do?
@PathVariable is used to pass parameter along with the url, sometimes we need to pass parameters along with the url to get the data. Spring MVC provides support for customizing the URL in order to get data. To achieving this purpose @PathVariable annotation is used in Spring mvc framework. Read More about PathVariable.

17. What is the HTTP status return code for a successful DELETE statement?
Either we can return HTTP status 204 (NO CONTENT) with no response body or return HTTP status 200 (OK) along with a response body with representation of the deleted item.

18. What does CRUD mean?
In Spring REST, the primary or most-commonly-used HTTP verbs are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively.

19. Is REST secure? What can you do to secure it?
REST is nothing but it architectural desgin or paradigms to design restful web service. So REST does not provide any security constraints by default but we can implement it in the RESTful web services by using security layers like transport layer security (TLS), auth token security.

20. Where do you need @EnableWebMVC?
@EnableWebMvc- It used for enabling spring mvc behavior i.e. it is responsible for registering Spring MVC required Bean Post Processors in the application as like Jackson2JsonMessageConverter etc.

21. Name some common http response codes. When do you need @ResponseStatus?

  • 2xx Success
    • 200 OK
    • 201 Created
    • 204 No Content
  • 3xx Redirection
    • 304 Not Modified
  • 4xx Client Error
    • 400 Bad Request
    • 401 Unauthorized
    • 403 Forbidden
    • 404 Not Found
    • 409 Conflict
  • 5xx Server Error
    • 500 Internal Server Error
    • 503 Service Unavailable

@ResponseStatus annotation available on custom exceptions and to map these exceptions to HTTP status codes.

22. Does REST work with transport layer security (TLS)?
Yes. Transport Layer Security can encrypt the communication to a RESTful Webservice and authenticate the server to a client.

23. Do you need Spring MVC in your classpath for Spring REST?
Yes, Spring REST uses the Spring MVC annotations like @RestController, @RequestBody and @ResponseBody etc.




Customizing HttpMessageConverter with Spring MVC in REST

Customizing HttpMessageConverter with Spring MVC in REST
HttpMessageConverter is a strategy interface that specifies a converter that can convert from and to HTTP requests and responses in Spring REST Restful web services. Internally Spring MVC uses it to convert the Http request to an object representation and back. Let's see following code for REST endpoint service.

@RestController
public class AccountController {
  @PostMapping("/account")
  public Account create (@RequestBody Account account){
     return accountService.create(account);
  }
}

Sending Request
Let's see API call for this endpoint. REST client consumes this endpoint with JSON object and we can specify "Content-Type" to be "application/json"

POST /restapi/account/ HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache

{
"name":"Arnav Rajput",
"city":"Noida",
"balance":4000202.33
}

Getting Response
We get back a 200 OK – a successful response as below:

HTTP/1.1 200 OK
Content-Type ?application/json;charset=UTF-8
Date ?Thu, 30 Mar 2017 12:46:49 GMT
Server ?Apache-Coyote/1.1
Transfer-Encoding ?chunked
{
  "accountId": 1,
  "name": "Arnav Rajput",
  "city": "Noida",
  "balance": 4000202.33
}

Client-Server Communication for this API Endpoint:

  • REST Client sends a POST request to /restapi/account/ with the Accept header set to application/json to get all Account resources as Json
  • AccountController is hit and returns the corresponding Account Java object as response
  • Now Spring Framework then uses one of the Jackson message converters to marshall and unmarshall Java Objects to and from JSON over HTTP.


In this above code we are using @RestController, it is actually combination of @ResponseBody and @Controller as of Spring 4.0, before it we have to specify with handler method as below:

@RequestMapping(value="/account", method=RequestMethod.POST)
public @ResponseBody Account create (@RequestBody Account account){
 return accountService.create(account);
}  

@ResponseBody
In Spring MVC, @ResponseBody annotation on a AccoutnController method indicates to Spring that the return Account object of the method is serialized to JSON directly to the body of the HTTP Response. It uses "Accept" header to choose the appropriate Http Converter to marshall the object.

@RequestBody
In Spring MVC, @RequestBody annotation on the argument of a AccountController method create (@RequestBody Account account) – it indicates to Spring that the body of the HTTP Request (either in JSON or XML) is deserialized to that Account Java Object. It uses "Content-Type" header specified by the REST Client will be used to determine the appropriate converter for this.

Default Message Converters in Spring MVC
In Spring MVC Framework, there is a set of default converters automatically registered which supports a whole range of different resource representation formats - json, xml for object. In RestTemplate in Spring REST, objects passed to and returned from the methods of RestTemplate class like getForObject(), postForLocation(), and put() are converted to HTTP requests and from HTTP responses by registered HttpMessageConverters.

  • StringHttpMessageConverter: it converts Strings from the HTTP request and response.
  • FormHttpMessageConverter: it converts form data to/from a MultiValueMap<String, String>.
  • ByteArrayHttpMessageConverter: it converts byte arrays from the HTTP request and response.
  • MappingJackson2HttpMessageConverter: it converts JSON from the HTTP request and response.
  • Jaxb2RootElementHttpMessageConverter: it converts Java objects to/from XML.
  • SourceHttpMessageConverter: it converts javax.xml.transform.Source from the HTTP request and response.
  • AtomFeedHttpMessageConverter: it converts Atom feeds.
  • RssChannelHttpMessageConverter: it converts RSS feeds.

Customizing HttpMessageConverters with Spring MVC
Let's see Spring MVC configuration file.

@Configuration
@EnableWebMvc
@ComponentScan("com.doj.restapi.web.controller")
public class WebConfiguration{
 
}

In the above MVC configuration file, we are using @EnableWebMvc annotation, it automatically registered default Http message converters with application as listed above according to available library in the class path. Now, if there is a need to customize the default message converters in some way. Spring provides a WebMvcConfigurerAdapter class, which allow us to change the default list of Http Converters with our own. Now let's below changed configuration class for Spring MVC.

/**
 * 
 */
package com.doj.restapi.web.config;

import java.util.List;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.doj.restapi.web.controller")
public class WebConfiguration extends WebMvcConfigurerAdapter{
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
 converters.add(createXmlHttpMessageConverter());
        converters.add(new MappingJackson2HttpMessageConverter());
        super.configureMessageConverters(converters);
    }
    private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
        MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
        XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
        xmlConverter.setMarshaller(xstreamMarshaller);
        xmlConverter.setUnmarshaller(xstreamMarshaller);
        return xmlConverter;
    }
}


Make sure that XStream library should be in the classpath of application. Here we are creating a new converter, the MarshallingHttpMessageConverter and we are using the Spring XStream support to configure it.

Summary
In this tutorial, we have seen how Spring MVC allows us to specify and fully customize Http Message Converters to automatically marshall/unmarshall Java Entities to and from XML or JSON.