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.