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.

Spring Restful Web Services XML CRUD Example

In this spring rest tutorial, we will create restful web services Crud APIs by using HTTP verbs GET, POST, PUT and Delete and returning XML representations of resources. In previous post, we have created a Spring Restful web services CRUD based example which returns json. In this post, we will see same example Spring Restful web services CRUD based on which will return xml.

If you want to learn more about REST you could read my previous article What is REST? Architecture and it’s Constraints. And also I have discussed how to consume Spring RESTful web services by RestTemplate read this article.

Technologies used in this example

  • Spring webmvc
  • Spring Data JPA
  • JAXB
  • Hibernate Entity Manager
  • H2 in-memory database

Let’s see steps to create a simple Spring Restful web services crud example which will return XML.

Step 1: Create a Dynamic web project using maven.

Project Structure

Spring Restful Web Services XML CRUD Example

Download Source Code from GitHub
Spring Restful Web Services XML CRUD Example

Step 2: Maven dependency for this application.
In pom.xml, there are following dependency required for this application.

<properties>
   <spring.version>4.3.5.RELEASE</spring.version>
   <spring.data.version>1.11.1.RELEASE</spring.data.version>
   <h2.version>1.4.193</h2.version>
  </properties>
  
  <dependencies>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>${spring.version}</version>
 </dependency>
 
 <dependency>
     <groupId>org.springframework.data</groupId>
     <artifactId>spring-data-jpa</artifactId>
     <version>${spring.data.version}</version>
 </dependency>
 
 <dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>${h2.version}</version>
 </dependency>
 
 <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.1.0.Final</version>
 </dependency>
  </dependencies>

If you want to include JSON response support as well then you need to do is include Jackson libraries into classpath, same APIs will work for jackson as well.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>

Step 3: Creating Spring Configuration files for this application
Here we are using Java based configuration. So let’s see following configuration java classes for this example.

a) Spring Configuration class for Spring MVC

RestApplicationConfig.java

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

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.doj.restapi.web.controller")
public class RestApplicationConfig{
 
}

b) Spring Configuration for application Infrastructure

This file has configuration about application core services like DB connection, DataSource and also scan the packages for service classes and repositories i.e. Non web components.

InfrastructureConfig.java

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

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@ComponentScan("com.doj.restapi.service")
@EnableJpaRepositories("com.doj.restapi.repository")
public class InfrastructureConfig {
 
 @Bean
 public DataSource dataSource() {
  return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
 }

 @Bean
 public JpaVendorAdapter jpaVendorAdapter() {
  HibernateJpaVendorAdapter bean = new HibernateJpaVendorAdapter();
  bean.setDatabase(Database.H2);
  bean.setGenerateDdl(true);
  return bean;
 }

 @Bean
 public LocalContainerEntityManagerFactoryBean entityManagerFactory(
   DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
  LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
  bean.setDataSource(dataSource);
  bean.setJpaVendorAdapter(jpaVendorAdapter);
  bean.setPackagesToScan("com.doj.restapi.bean");
  return bean;
 }

 @Bean
 public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
  return new JpaTransactionManager(emf);
 }
}

Step 4: Creating Web Application Initializer file for this application
In this example we are using Java Based web application configuration instead of traditional web.xml file and for this we have required at least tomcat 7 and servlet 3.0+ .

RestApplicationInitializer.java

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

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.doj.restapi.config.InfrastructureConfig;
import com.doj.restapi.web.config.RestApplicationConfig;

/**
 * @author Dinesh.Rajput
 *
 */
public class RestApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
  return new Class[] { InfrastructureConfig.class };
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class[] { RestApplicationConfig.class };
 }

 @Override
 protected String[] getServletMappings() {
  return new String[] { "/" };
 }
}

Step 5: Creating Application classes
In this application, we will create and read account resource from account repository.
a) Create a Controller AccountController.java

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

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.bean.AccountList;
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 AccountList 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);
 }
}

In this controller class we have used @RestController annotation. Till Spring 3, we would have been using @Controller annotation and in that case it was important to use @ResponseBody annotation as well as below:

@Controller
public class AccountController {
.....
.....

@RequestMapping("/account/{accountId}")
public  @ResponseBody Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}
.....
.....
}

As of spring 4.0, we can use @RestController which is combination of @Controller and @ResponseBody. Read my article RestController in Spring Framework 4.0 for more detail.

@RestController = @Controller + @ResponseBody

In this example, we are using @GetMapping, @PostMapping, @PutMapping and @DeleteMapping annotations, these annotations are introduced from Spring 4.3 version in parallel of @RequestMapping with Http Methods annotation as below.

@GetMapping = @RequestMapping + Http GET method
@PostMapping = @RequestMapping + Http POST method
@PutMapping = @RequestMapping + Http PUT method
@DeleteMapping = @RequestMapping + Http DELETE method

Spring provides HttpMessageConverters to convert an object to the xml representation requested by the user. Spring’s @ResponseBody annotation is responsible for generating body response by using result of the method to the client. In this example we want XML response so this marshaling is done by the Jaxb2RootElementHttpMessageConverter provided by Spring which is automatically registered in spring context if JAXB libraries are found in classpath. JAXB library is inbuilt in the java from JDK 7.0 here I am using JDK 8 in this application, so there is no need to configure JAXB library into Maven dependency file.

b) JAXB Annotated Model Objects
We need to annotate bean class with @XmlRootElement and @XmlElement to support for xml.

Account.java

/**
 * 
 */
package com.doj.restapi.bean;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh.Rajput
 *
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE) 
@Entity
@Table
public class Account implements Serializable{
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 
 @XmlAttribute
 @Id
 @GeneratedValue
 public Long accountId;
 
 @XmlElement
 public String name;
 
 @XmlElement
 public String city;
 
 @XmlElement
 public Double balance;
 
 public Account() {
  super();
 }
 public Account(String name, String city, Double balance) {
  super();
  this.name = name;
  this.city = city;
  this.balance = balance;
 }
 public Long getAccountId() {
  return accountId;
 }
 public void setAccountId(Long accountId) {
  this.accountId = accountId;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public Double getBalance() {
  return balance;
 }
 public void setBalance(Double balance) {
  this.balance = balance;
 }
 @Override
 public String toString() {
  return "Account [accountId=" + accountId + ", name=" + name + ", city=" + city + ", balance=" + balance + "]";
 }
 
}

AccountList.java

/**
 * 
 */
package com.doj.restapi.bean;

import java.io.Serializable;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh.Rajput
 *
 */
@XmlRootElement (name="accounts")
public class AccountList implements Serializable {

 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 
 private List<Account> listOfAccounts;

 public List<Account> getListOfAccounts() {
  return listOfAccounts;
 }
 @XmlElement(name = "account")
 public void setListOfAccounts(List<Account> listOfAccounts) {
  this.listOfAccounts = listOfAccounts;
 }
 
}

c) Create a Service class AccountService.java
This class has CRUD method service for account resource.

AccountService.java

/**
 * 
 */
package com.doj.restapi.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.doj.restapi.bean.Account;
import com.doj.restapi.bean.AccountList;
import com.doj.restapi.repository.AccountRepository;

/**
 * @author Dinesh.Rajput
 *
 */
@Service
public class AccountService implements IAccountService{
 
 @Autowired
 AccountRepository accountRepository;
 
 @Override
 public Account create(Account account) {
  return accountRepository.save(account);
 }

 @Override
 public Account get(Long accountId) {
  return accountRepository.findOne(accountId);
 }

 @Override
 public Account update(Account account) {
  return accountRepository.save(account);
 }

 @Override
 public void delete(Long accountId) {
  accountRepository.delete(accountId);
 }

 @Override
 public AccountList list() {
  AccountList accountList = new AccountList();
  Iterable<Account> itr = accountRepository.findAll();
  List<Account> accounts = new ArrayList<Account>();
  for(Account account : itr){
   accounts.add(account);
  }
  accountList.setListOfAccounts(accounts);
  return accountList;
 }
}

d) Create a Repository class AccountRepository.java
This is an interface which extends an interface of Spring Data JPA for using CRUD operation over account class.

/**
 * 
 */
package com.doj.restapi.repository;

import org.springframework.data.repository.CrudRepository;

import com.doj.restapi.bean.Account;

/**
 * @author Dinesh.Rajput
 *
 */
public interface AccountRepository extends CrudRepository {

}

Step 6: Deploying this application to tomcat server

Right click on project -> run as -> run on server

After starting of tomcat server, Let’s check our application with Rest client Postman, it is UI based client for testing restful web applications, postman is chrome plugin. Launch postman.

a) POST method: CREATE Account Resource using POST http method
Post method is used to create new resource. Here we are adding new Account to the account database, so you can see we have used account XML in post body.

Spring-REST-POST

b) GET method: READ Account Resource using GET http method
Test our get method Spring REST service. You will get following output as below:

Spring-REST-GET

c) PUT method: UPDATE Account Resource using PUT http method
Put method is used to update resource. Here we will update name of account holder of accountId=1 using put method. So we will update account XML in body of request of accountId is 1 as below.

Spring-REST-PUT

d) Read All Account Resources using GET http method

Read ALL

e) DELETE method: DELETE Account Resource using DELETE http method
Delete method is used to delete resource. So here we will pass accountId of account which needs to be deleted as Path Param. We are going delete the account who have accountId=1.

Spring-REST-DELETE

f) Read All Accounts after DELETE Call

Spring-REST-After-delete

Spring REST client – RestTemplate Consume RESTful Web Service Example JSON

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 param, request object and response type as arguments.

In this example, we will see how to consume JSON response. In my previous article we have seen Spring RESTful web services crud example. Earlier we have used postman REST UI based client to demonstrate all HTTP methods such as get, post, delete and put. But here we are going to consume Restful web services via RestTemplate of Spring REST client.

RestTemplate Methods
RestTemplate provides higher level methods that correspond to each of the six main HTTP methods that make invoking many RESTful services. In the following list has methods provided by Spring RestTemplate for each http methods.

Method

Spring RestTemplate’s method

Get

 getForObject, getForEntity

Post

postForObject(String url, Object request, Class responseType, String…? uriVariables)

postForLocation(String url, Object request, String…? urlVariables),

Put

put(String url, Object request, String…?urlVariables)

Delete

delete()

Head

headForHeaders(String url, String…? urlVariables)

Options

optionsForAllow(String url, String…? urlVariables)

As per as name of these methods of RestTemplate class indicate which HTTP method they implement internally and second part of the method name indicates what is return by these methods. For example, getForObject() will perform a HTTP GET action on the server, and convert the HTTP response into an object of given type and return it to the client. And other method postForLocation() will do a HTTP POST action on the server, converting the given object into a HTTP request, and returns the response HTTP Location header where the newly created object can be found.

Let’s see these RestTemplate’s methods with examples.
 Here I am using Spring Restful web services CRUD JSON Example of my previous post.

In this example, we are using @GetMapping, @PostMapping, @PutMapping and @DeleteMapping annotations, these annotations are introduced as of Spring 4.3 version in parallel of @RequestMapping annotation with Http Methods as below.

@GetMapping = @RequestMapping + Http GET method
@PostMapping = @RequestMapping + Http POST method
@PutMapping = @RequestMapping + Http PUT method
@DeleteMapping = @RequestMapping + Http DELETE method

HTTP GET Method Example
For API GET method call we can use either getForObject() or getForEntity() method of RestTemplate.

Spring REST API GET CODE:

@GetMapping("/account/{accountId}")
public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}

We could define same above API call as below:

@RequestMapping(method=RequestMethod.GET, value = "/account/{accountId}", produces = MediaType.APPLICATION_JSON_VALUE)
public Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}

This call binds to convert on JSON media type only with the @RequestMapping annotation. If you want flexible return media type either JSON or XML based on the message converter available on the classpath of the application then it’s recommend do not define produces property request mapping annotation.

Spring RestTemplate get Method :

/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Read Account details for a given accountId = 1 using GET method of RestTemplate
  Account accountDetail = restTemplate.getForObject(baseURL+"account/1", Account.class);
  System.out.println("Account Detail for given AccountId : " +accountDetail); 
  
 }

}

Output on console:
After running above code, you will get below output:

Account Detail for given AccountId : Account [accountId=1, name=Dinesh Rajput, city=Noida, balance=212.33]

HTTP POST Method Example

For Http POST method calling we can use either postForObject() or postForLocation() method of RestTemplate.

Spring Rest API Code post method:

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

Spring RestTemplate post Method call:

/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Create Account using POST method of RestTemplate
  Account account = new Account("Arnav Rajput", "Noida", 312.33);
  account = restTemplate.postForObject(baseURL+"account", account, Account.class);
  System.out.println("Added account: " +account);
  
 }

}

Output on console:
After running above code, you will get below output:

Added account: Account [accountId=3, name=Arnav Rajput, city=Noida, balance=312.33]

HTTP PUT Method Example

For Http PUT method calling we can use put() method of RestTemplate.

Spring Rest API Code put method:

@PutMapping("/account")
public Account update (@RequestBody Account account){
  return accountService.update(account);
}

Spring RestTemplate put Method call:

/**
 * 
 */
package com.doj.restclient.account;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  //Create Account using POST method of RestTemplate
  Account account = new Account("Arnav Rajput", "Noida", 312.33);
  account = restTemplate.postForObject(baseURL+"account", account, Account.class);
  System.out.println("Added account: " +account);
  
  //Update Account detail for given accountId = 1 using PUT method of RestTemplate
  Account updateAccount = new Account("Anamika Rajput", "Noida", 123.33);
  updateAccount.setAccountId(1l);
  restTemplate.put(baseURL+"account", updateAccount);
  Account updatedAccount = restTemplate.getForObject(baseURL+"account/1", Account.class);
  System.out.println("Updated Account: " +updatedAccount);
  
 }

}

Output on console:
After running above code, you will get below output:

Added account: Account [accountId=1, name=Arnav Rajput, city=Noida, balance=312.33]
Updated Account: Account [accountId=1, name=Anamika Rajput, city=Noida, balance=123.33]

HTTP DELETE Method Example

For Http DELETE method calling we can use delete() method of RestTemplate.

Spring Rest API Code delete method:

@DeleteMapping("/account/{accountId}")
public void delete (@PathVariable Long accountId){
  accountService.delete(accountId);
}

Spring RestTemplate delete Method call:

/**
 * 
 */
package com.doj.restclient.account;

import java.util.List;

import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class SpringRestClient {
 
 private static RestTemplate restTemplate = new RestTemplate();
 private static final String baseURL = "http://localhost:8080/restapi/";

 /**
  * @param args
  */
 public static void main(String[] args) {
  List<Account> accounts = restTemplate.getForObject(baseURL+"accounts", List.class);
  System.out.println("Total Accounts before DELETE call: ");
  for(Object acct : accounts){
   System.out.println(acct);
  }
  
  //Delete Account for given accountId = 2 using Delete method of RestTemplate
  restTemplate.delete(baseURL+"account/2");
  accounts = restTemplate.getForObject(baseURL+"accounts", List.class);
  System.out.println("Total Accounts after DELETE call: ");
  for(Object acct : accounts){
   System.out.println(acct);
  }
 }

}

Output on console:
After running above code, you will get below output:

Total Accounts before DELETE call:
{accountId=1, name=Anamika Rajput, city=Noida, balance=123.33}
{accountId=2, name=Anamika Rajput, city=Noida, balance=222.33}
{accountId=3, name=Arnav Rajput, city=Noida, balance=522.33}
Total Accounts after DELETE call:
{accountId=1, name=Anamika Rajput, city=Noida, balance=123.33}
{accountId=3, name=Arnav Rajput, city=Noida, balance=522.33}

Download Source Code from GitHub.

  1. Spring RESTful web service CRUD Example
  2. Spring REST Client using RestTemplate Example
Spring REST client – RestTemplate Consume RESTful Web Service Example JSON

Spring Restful Web Services JSON CRUD Example

In this spring rest tutorial, we will create restful web services Crud APIs by using HTTP verbs GET, POST, PUT and Delete and returning JSON representations of resources. In my previous post, we have created a very simple JAX-RS Restful web services but in this post we are using Spring REST, it will return response as json in this example. If you want to learn more about REST you could read my previous article What is REST? Architecture and it’s Constraints.

Here we are using Spring 4.3.5 webmvc, Spring REST, Spring Data JPA and jackson libraries for this example. For back-end we are using H2 in-memory database for saving the data and also using Spring Data JPA over the Hibernate JPA as ORM. Let’s see steps to create a simple Spring Restful web services crud example which will return json.

Step 1: Create a Dynamic web project using maven.

Project Structure

Spring Restful Web Services JSON CRUD Example

Download Source Code from GitHub
Spring Restful Web Services JSON CRUD Example

Step 2: Maven dependency for this application.
In pom.xml, there are following dependency required for this application.

<properties>
   <spring.version>4.3.5.RELEASE</spring.version>
   <spring.data.version>1.11.1.RELEASE</spring.data.version>
   <h2.version>1.4.193</h2.version>
  </properties>
  
  <dependencies>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>${spring.version}</version>
 </dependency>
 
 <dependency>
     <groupId>org.springframework.data</groupId>
     <artifactId>spring-data-jpa</artifactId>
     <version>${spring.data.version}</version>
 </dependency>
 
 <dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>${h2.version}</version>
 </dependency>
 
 <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.1.0.Final</version>
 </dependency>
 
 <!-- Jackson JSON Mapper -->
       <dependency>
           <groupId>org.codehaus.jackson</groupId>
           <artifactId>jackson-mapper-asl</artifactId>
           <version>1.7.1</version>
       </dependency>
       <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.5.0</version>
 </dependency>
  </dependencies>

In the maven file we have dependencies of spring webmvc, spring data jpa, h2 database and hibernate entity manager for jpa transaction. Also we have to include jackson maven dependencies into classpath of your application because spring will register Jackson2JsonMessageConverter class automatically into context. Whenever we request resource as json with accept headers=”Accept=application/json”, then Jackson2JsonMessageConverter comes into picture and convert resource to json format.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>

Step 3: Creating Spring Configuration files for this application
In this spring restful web service application, we are using Java based configuration. So let’s see following configuration java classes for this example.

a) Spring Configuration class for Spring MVC
The following file is required for configuring spring mvc to the application and enabling required bean post processors for message converter.

RestApplicationConfig.java

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

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.doj.restapi.web.controller")
public class RestApplicationConfig{
 
}

@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.
@ComponentScan- It scans the package com.doj.restapi.web.controller. This package has Rest Controllers for this application.

b) Spring Configuration for application Infrastructure
This file has configuration about application core services like DB connection, DataSource and also scan the packages for service classes and repositories i.e. Non web components.

InfrastructureConfig.java

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

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@ComponentScan("com.doj.restapi.service")
@EnableJpaRepositories("com.doj.restapi.repository")
public class InfrastructureConfig {
 
 @Bean
 public DataSource dataSource() {
  return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
 }

 @Bean
 public JpaVendorAdapter jpaVendorAdapter() {
  HibernateJpaVendorAdapter bean = new HibernateJpaVendorAdapter();
  bean.setDatabase(Database.H2);
  bean.setGenerateDdl(true);
  return bean;
 }

 @Bean
 public LocalContainerEntityManagerFactoryBean entityManagerFactory(
   DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
  LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
  bean.setDataSource(dataSource);
  bean.setJpaVendorAdapter(jpaVendorAdapter);
  bean.setPackagesToScan("com.doj.restapi.bean");
  return bean;
 }

 @Bean
 public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
  return new JpaTransactionManager(emf);
 }
}

@EnableJpaRepositories-It used to create the spring bean related to spring data jpa in the application i.e. those classes which implement spring data repository interfaces.

Step 4: Creating Web Application Initializer file for this application
Here we are using Java based configuration for web application i.e. here we do not have web.xml file in the application. For java based web configuration, we have to required at least tomcat 7 and servlet 3.0 or above.

RestApplicationInitializer.java

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

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.doj.restapi.config.InfrastructureConfig;
import com.doj.restapi.web.config.RestApplicationConfig;

/**
 * @author Dinesh.Rajput
 *
 */
public class RestApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
  return new Class[] { InfrastructureConfig.class };
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class[] { RestApplicationConfig.class };
 }

 @Override
 protected String[] getServletMappings() {
  return new String[] { "/" };
 }
}

Step 5: Creating Application classes
In this application, we will create and read account resource from account repository.
a) Create a Controller AccountController.java

/**
 * 
 */
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/{accountId}")
 public Account update (@RequestBody Account account, @PathVariable Long accountId){
  return accountService.update(account, accountId);
 }
 
 @DeleteMapping("/account/{accountId}")
 public void delete (@PathVariable Long accountId){
  accountService.delete(accountId);
 }
}

This controller class is annotated with @RestController annotation instead of @Controller annotation. As of spring 4.0, we can use @RestController which is combination of @Controller and @ResponseBody. Read my article RestController in Spring Framework 4.0 for more detail.

@RestController = @Controller + @ResponseBody

Before Spring 4.0, we have to use @Controller at the class level with @ResponseBody before the handler method as below:

@Controller
public class AccountController {
.....
.....

@RequestMapping("/account/{accountId}")
public  @ResponseBody Account get (@PathVariable Long accountId){
  return accountService.get(accountId);
}
.....
.....
}

In this example, we are using @GetMapping, @PostMapping, @PutMapping and @DeleteMapping annotations, these annotations are introduced from Spring 4.3 version in parallel of @RequestMapping with Http Methods annotation as below.

@GetMapping = @RequestMapping + Http GET method

b) Create a Bean class Account.java

/**
 * 
 */
package com.doj.restapi.bean;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author Dinesh.Rajput
 *
 */
@Entity
@Table
public class Account implements Serializable{
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 @Id
 @GeneratedValue
 public Long accountId;
 public String name;
 public String city;
 public Double balance;
 
 public Account() {
  super();
 }
 public Account(String name, String city, Double balance) {
  super();
  this.name = name;
  this.city = city;
  this.balance = balance;
 }
 public Long getAccountId() {
  return accountId;
 }
 public void setAccountId(Long accountId) {
  this.accountId = accountId;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public Double getBalance() {
  return balance;
 }
 public void setBalance(Double balance) {
  this.balance = balance;
 }
 @Override
 public String toString() {
  return "Account [accountId=" + accountId + ", name=" + name + ", city=" + city + ", balance=" + balance + "]";
 }
 
}

c) Create a Service class AccountService.java
This class has CRUD method service for account resource.

/**
 * 
 */
package com.doj.restapi.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.doj.restapi.bean.Account;
import com.doj.restapi.repository.AccountRepository;

/**
 * @author Dinesh.Rajput
 *
 */
@Service
public class AccountService implements IAccountService{
 
 @Autowired
 AccountRepository accountRepository;
 
 @Override
 public Account create(Account account) {
  return accountRepository.save(account);
 }

 @Override
 public Account get(Long accountId) {
  return accountRepository.findOne(accountId);
 }

 @Override
 public Account update(Account account, Long accountId) {
  return accountRepository.save(account);
 }

 @Override
 public void delete(Long accountId) {
  accountRepository.delete(accountId);
 }

 @Override
 public List<Account> list() {
  return (List<Account>) accountRepository.findAll();
 }
}

d) Create a Repository class AccountRepository.java
This is an interface which extends an interface of Spring Data JPA for using CRUD operation over account class.

/**
 * 
 */
package com.doj.restapi.repository;

import org.springframework.data.repository.CrudRepository;

import com.doj.restapi.bean.Account;

/**
 * @author Dinesh.Rajput
 *
 */
public interface AccountRepository extends CrudRepository<Account, Long> {

}

This interface is extending an interface CrudRepository of Spring Data JPA library. As you seen, there is no method in the interface, so we are using default CRUD operation methods of CrudRepository interface.

Step 6: Deploying this application to tomcat server

Right click on project -> run as -> run on server

After starting of tomcat server, Let’s check our application with Rest client Postman, it is UI based client for testing restful web applications, we have below URL of our application to provide start page:

a) Home Page
http://localhost:8080/restapi/

rest-home-page

Postman is chrome plugin. Launch postman.
b) POST method: CREATE Account Resource using POST http method
Post method is used to create new resource. Here we are adding new Account to the account database, so you can see we have used account json in post body.

Create-resource-POST-method

c) GET method: READ Account Resource using GET http method
Test our get method Spring REST service. You will get following output as below:

Read-Resource-Http-GET

d) PUT method: UPDATE Account Resource using PUT http method
Put method is used to update resource. Here we will update name of account holder of accountId=1 using put method. So we will update account json in body of request of accountId is 1 as below.

Spring Restful webservice Http PUT method

e) DELETE method: DELETE Account Resource using DELETE http method
Delete method is used to delete resource. So here we will pass accountId of account which needs to be deleted as Path Param. We are going delete the account who have accountId=3.

Spring Restful webservice Http DELETE method

f) Read All Account Resources using GET http method

All accounts

Create Custom Bean Scope in Spring Example

There are two main scopes of bean in spring singleton and prototype but spring allow us to create custom bean scope too through the interface Scope in the spring Example. As of Spring 2.0, we can define custom spring bean scope as well as modify existing spring bean scopes (except singleton and prototype scopes). So let’s see how to create custom spring bean scope with example.

Create Custom Bean Scope Class
Let’s have a look into below class MyThreadScope.java

/**
 * 
 */
package com.doj.app.scope;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * @author Dinesh.Rajput
 *
 */
public class MyThreadScope implements Scope {
 
 private final ThreadLocal<Object> myThreadScope = new ThreadLocal<Object>() {
  protected Map<String, Object> initialValue() {
   System.out.println("initialize ThreadLocal");
   return new HashMap<String, Object>();
  }
 };
  
 @SuppressWarnings("unchecked")
 @Override
 public Object get(String name, ObjectFactory<?> objectFactory) {
  Map<String, Object> scope = (Map<String, Object>) myThreadScope.get();
  System.out.println("getting object from scope.");
  Object object = scope.get(name);
  if(object == null) {
   object = objectFactory.getObject();
   scope.put(name, object);
  }
  return object;
 }

 @Override
 public String getConversationId() {
  return null;
 }

 @Override
 public void registerDestructionCallback(String name, Runnable callback) {

 }

 @Override
 public Object remove(String name) {
  System.out.println("removing object from scope.");
  @SuppressWarnings("unchecked")
  Map<String, Object> scope = (Map<String, Object>) myThreadScope.get();
  return scope.remove(name);
 }

 @Override
 public Object resolveContextualObject(String name) {
  return null;
 }

}

As above class for custom scope MyThreadScope, we have implemented org.springframework.beans.factory.config.Scope interface to create a own custom scope in the spring container. This interface contain five methods. But following two mandatory methods have to override to create custom spring bean scope.

  • get() method – this method return the bean from the given scope.
  • remove() method – this method remove an object from the scope

Register Created Custom Bean Scope
After creating the custom bean scope, we have to register it with the spring container. So there are two way to register it. Either by it programmatic registration or we can do it via using XML based configuration. Let’s have a look into both configuration as below:

Java Based Configuration:

ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Scope scope = new MyThreadScope();
applicationContext.getBeanFactory().registerScope("myThreadScope", scope);

XML Based Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
 <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
  <property name="scopes">
   <map>
               <entry key="myThreadScope">
                   <bean class="com.doj.app.scope.MyThreadScope"/>
               </entry>
           </map>
  </property>
 </bean>
 
 <bean id="myBean" class="com.doj.app.bean.MyBean" scope="myThreadScope"> 
  <property name="name" value="Dinesh"></property>
 </bean>
</beans>

Using the custom scope
In XML

<bean id="myBean" class="com.doj.app.bean.MyBean" scope="myThreadScope"> 
   <property name="name" value="Dinesh"></property>
</bean>

In Java

@Bean
@Scope("myThreadScope")
MyBean myBean(){
   return new MyBean();
}

Test Class for Custom Scope Example
Main.java

/**
 * 
 */
package com.doj.app.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.doj.app.bean.MyBean;

/**
 * @author Dinesh.Rajput
 *
 */
public class Main {
 /**
  * @param args
  */
 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  MyBean myBean = applicationContext.getBean(MyBean.class);
  System.out.println(myBean.getName());
  System.out.println("All registered Scopes are : ");
  for(String scope : applicationContext.getBeanFactory().getRegisteredScopeNames()){
   System.out.println(scope);
  }
  applicationContext.close();
 }

}

Output on Console:

Mar 24, 2017 7:52:44 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Fri Mar 24 07:52:44 IST 2017]; root of context hierarchy
Mar 24, 2017 7:52:44 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
initialize ThreadLocal
getting object from scope.
Dinesh
All registered Scopes are :
myThreadScope
Mar 24, 2017 7:52:44 AM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Fri Mar 24 07:52:44 IST 2017]; root of context hierarchy

Custom Bean Scope Example with Source Code

Download this example from Github.

Create Custom Bean Scope in Spring Example

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Get the Best Spring AOP Framework Tutorial

Spring AOP Tutorial with Example

In this Spring AOP Tutorial, We have lot of Examples of Creating Spring Aspect using annotation @Aspect, Declaring @Pointcut for Join Point and declaring different advice by using annotation based configuration @Before, @After, @Around annotations and also examples of XML-based or Schema based configuration. And also we will discuss about AOP Proxy.

What is AOP?

AOP stands for Aspect Oriented Programming, It compliments OOPs in the different sense of concern, it also provides modularity. But in AOP the key unit of modularity is aspect than class and this aspects enable the modularization of concerns such as logging, security and transaction management. And these concerns cut across multiple types and objects in the application and these are commonly also known as crosscutting concerns of the application.

What are Cross-Cutting Concerns?
• Generic functionality that is needed in many places in your application
• Examples
– Logging and Tracing
– Transaction Management
– Security
– Caching
– Error Handling
– Performance Monitoring
– Custom Business Rules

System Without AOP or Modularization
There are two main problems
– Code tangling
• A coupling of concerns
– Code scattering
• The same concern spread across modules


System Without AOP or Modularization

System With AOP or Modularization
Aspect-Oriented Programming (AOP) enables modularization of cross-cutting concerns
– To avoid tangling
– To eliminate scattering

System With AOP or Modularization

Core AOP Concepts
Join Point
– A point in the execution of a program such as a method call or exception thrown
Pointcut
– An expression that selects one or more Join Points
Advice
– Code to be executed at each selected Join Point
Aspect
– A module that encapsulates pointcuts and advice
Weaving
– Technique by which aspects are combined with main code

Spring AOP Tutorial with Example
Read below examples to know more about implementing each advice in detail.

Spring AOP Interview Questions
Top 20 Spring AOP Interview Questions and Answers
Some most asked spring AOP interview questions in java interviews.
Spring AOP AspectJ Annotations and Java Based Configuration

Spring AOP AspectJ Annotation Java Based Config Example
Learn to configure AOP aspects using aspectj annotations configuration.

Spring AOP AspectJ @Before Example Java Based Configuration
Learn to configure aop before advice aspect using @Before annotation.

Spring AOP AspectJ @After Example Java Based Configuration
Learn to configure aop after advice aspect using @After annotation.

Spring AOP AspectJ @Around Example Java Based Configuration
Learn to configure aop around advice aspect using @Around annotation.

Spring AOP AspectJ @AfterReturning Example Java Based Configuration
Learn to configure aop after returning advice aspect using @AfterReturning annotation.

Spring AOP AspectJ @AfterThrowing Example Java Based Configuration
Learn to configure aop after throwing advice aspect using @AfterThrowing annotation.

Spring AOP Schema Based Examples XML Configuration

Spring AOP AspectJ XML Configuration Example
Learn to configure AOP aspects using XML configuration.

Spring AOP Before Advice XML Configuration Example
Learn to configure aop before advice aspect using <aop:before/> configuration.

Spring AOP After Returning Advice XML Configuration Example
Learn to configure aop after returning advice aspect using <aop:after-returning/> configuration.

Spring AOP After Throwing Advice XML Configuration Example
Learn to configure aop after throwing advice aspect using <aop:after-throwing/> configuration.

Spring AOP After Advice XML Configuration Example
Learn to configure aop after advice aspect using <aop:after/> configuration.

Spring AOP Around Advice XML Configuration Example
Learn to configure aop around advice aspect using <aop:around/> configuration.

Other Spring AOP Tutorials
Spring AOP-Ordering of Aspects with Example
Learn to order the aspect execution in case of multiple aspects which need to be executed in certain order.

Spring AOP-Declaring pointcut Expressions with Examples
Learn to write point cut expressions to match a variety of joint points.

Spring AOP-Introduction to Aspect Oriented Programming
Learn what is need of Aspect Oriented Programming in the application.

Spring AOP- JoinPoints and Advice Arguments
Learn about Spring AOP JoinPoints and advice arguments.

Spring AOP- Writing First AspectJ Program in Spring
Creating AspectJ program in the Spring AOP.

Spring AOP Proxies
Learn about how to work AOP proxies behind.

Spring AOP-Ordering of Aspects with Example

In Spring AOP aspects ordering tutorial, we will discuss how to use @Order annotation and Order interface to decide precedence/order of the aspects applied to the same join point. In my last tutorials of Spring AOP advice, you have seen that we have applied single Aspect to a join point. In real time projects, we have to use multiple aspects in our application and these aspects can be applied on a certain method. So in this situation there are more than one aspect applied to the same join point. In this case, the order of execution of the aspects will not be determined unless we have explicitly specified by using either @Order annotation or org.springframework.core.Ordered interface.

Download Application Source Code
SpringAOP-Aspects-Order-Example from Github.

Let’s see Aspects Ordering with the example. In this example we have three aspects LoggingAspect, SecurityAspect and TransactionAspect for same join point transfer() method of TransferService class in the com.doj.aopapp.service package. Suppose we want to apply these aspects in the following order to the same join point (transfer() target method of TransferSerivce).

  1. SecurityAspect
  2. TransactionAspect
  3. LoggingAspect

So, achieving this order of aspects we using two ways.

  1. @Order Annoation
  2. org.springframework.core.Ordered interface

1. Specifying order by using @Order annotation
This is very simple way. Use the annotation as below.

SecurityAspect.java

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
@Order(0)
public class SecurityAspect {
 
 /**
  * Declaring before advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****SecurityAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }
}

TransactionAspect.java

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
@Order(1)
public class TransactionAspect {
 
 /**
  * Declaring before advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****TransactionAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }
 
}

LoggingAspect.java

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
@Order(2)
public class LoggingAspect {
 
 /**
  * Declaring around advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @Around("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("****LoggingAspect Before execution of Transfer Methods " + pjp.getSignature().getName());
        pjp.proceed();
        System.out.println("****LoggingAspect After execution of Transfer Methods " + pjp.getSignature().getName());
    }
}

2. Specifying order by using org.springframework.core.Ordered interface
This is also very simple way. Use the interface as below.

SecurityAspect.java

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class SecurityAspect implements Ordered{
 
 /**
  * Declaring before advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****SecurityAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }

 @Override
 public int getOrder() {
  return 0;
 }
}

TransactionAspect.java

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class TransactionAspect implements Ordered{
 
 /**
  * Declaring before advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****TransactionAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }

 @Override
 public int getOrder() {
  return 1;
 }
 
}

LoggingAspect.java

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class LoggingAspect implements Ordered {
 
 /**
  * Declaring around advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @Around("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("****LoggingAspect Before execution of Transfer Methods " + pjp.getSignature().getName());
        pjp.proceed();
        System.out.println("****LoggingAspect After execution of Transfer Methods " + pjp.getSignature().getName());
    }

 @Override
 public int getOrder() {
  return 2;
 }
}

ApplicationContext Configuration file based on Java Config
AppConfig.java

/**
 * 
 */
package com.doj.aopapp.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages={"com.doj.aopapp.aspect", "com.doj.aopapp.service"})
public class AppConfig {
 
}

ApplicationContext Configuration file based on XML Config
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <aop:config>
  <aop:aspect ref="securityAspect" order="0">
   <!-- all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
   <aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>
   <aop:before method="beforeAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
  <aop:aspect ref="transactionAspect" order="1">
   <!-- all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
   <aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>
   <aop:before method="beforeAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
  <aop:aspect ref="loggingAspect" order="2">
   <!-- all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
   <aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>
   <aop:around method="beforeAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
 </aop:config>
 
 <bean id="transferService" class="com.doj.aopapp.service.TransferServiceImpl"/>
 <bean id="securityAspect" class="com.doj.aopapp.aspect.SecurityAspect"/>
<bean id="transactionAspect" class="com.doj.aopapp.aspect.TransactionAspect"/>
 <bean id="loggingAspect" class="com.doj.aopapp.aspect.LoggingAspect"/>
</beans>

Test Class for Spring AspectJ Configuration and Execution
Let’s run the example as below:

/**
 * 
 */
package com.doj.aopapp.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.doj.aopapp.config.AppConfig;
import com.doj.aopapp.service.TransferService;

/**
 * @author Dinesh.Rajput
 *
 */
public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
  TransferService transferService = applicationContext.getBean(TransferService.class);
  transferService.transfer("accountA", "accountB", 50000l);
  applicationContext.close();
 }

}

Output on the Console:

Mar 20, 2017 5:59:16 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Mon Mar 20 17:59:16 IST 2017]; root of context hierarchy
****SecurityAspect.beforeAdviceForTransferMethods() transfer
****TransactionAspect.beforeAdviceForTransferMethods() transfer
****LoggingAspect Before execution of Transfer Methods transfer
50000 Amount has been tranfered from accountA to accountB
****LoggingAspect After execution of Transfer Methods transfer
Mar 20, 2017 5:59:17 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Mon Mar 20 17:59:16 IST 2017]; root of context hierarchy

As per as output on the console Spring AOP aspects ordering is working as expected.

Spring AOP Related Posts

  1. Spring AOP Interview Questions and Answers
  2. Spring AOP Tutorial- Aspect Oriented Programming with Spring
  3. @Aspect Annotation in Spring
  4. Advices in Spring AOP
  5. Spring AOP JoinPoints and Advice Arguments
  6. Spring AOP Pointcuts and Wildcard Expressions
  7. Spring AOP XML configuration
  8. Spring AOP XML Schema based Example
  9. Spring AOP AspectJ @Before Annotation Advice Example
  10. Spring AOP Before Advice Example using XML Config
  11. Spring AOP AspectJ @After Annotation Advice Example
  12. Spring AOP After Advice Example using XML Config
  13. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  14. Spring AOP After-Returning Advice Example using XML Config
  15. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  16. Spring AOP After Throwing Advice Example using XML Config
  17. Spring AOP AspectJ @Around Annotation Advice Example
  18. Spring AOP Around Advice Example using XML Config
  19. Spring AOP Writing First AspectJ Program in Spring
  20. Spring AOP Proxies in Spring
  21. Spring AOP Transaction Management in Hibernate
  22. Spring Transaction Management
  23. Spring Declarative Transaction Management Example

Spring AOP Around Advice Example using XML Config

In this spring aop example of around advice with XML configuration, we learn how to use Spring AOP Around advice using <aop:around/> XML namespace  configuration. In Spring AOP, Around Advice to be executed if a method exits by throwing an exception i.e  Any methods configured as Around advice always run immediately after the target methods throws any exception.

Download Application Source Code

Spring AOP Around Advice Example using XML Config on GitHub.

Let’s create a simple spring application and add logging aspect to be invoked on based on pointcuts information passed in <aop:around/> xml configuration. This example is also available with Java configuration Spring AOP AspectJ @Around Annotation Advice Example.

Configuring Spring AOP After Throwing Advice using aop namespace <aop:around/>
In this example, we are using <aop:*/> namespace for XML configuration. So here we have to add <aop:around/> aop namespace in our XML configuration file in this example. Let’s see our aop configuration for after advice in this example.

Let’s create a simple spring application and add logging aspect to be invoked on based on pointcuts information passed in <aop:around/> xml configuration.

<aop:config>
  <aop:aspect ref="loggingAspect">
    <!-- all public methods with any arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
    <aop:pointcut expression="execution(* com.doj.aopapp.service.*.*(..))" id="logForAllMethods"/>
    <!-- all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
    <aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>
    <aop:around method="aroundAdviceForAllMethods" pointcut-ref="logForAllMethods"/>
    <aop:around method="aroundAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
</aop:config>

Declaring Pointcut expressions
#1. In First pointcut expression, we have declared after throwing advice, it is valid for all public methods with any number of arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

<aop:pointcut expression="execution(* com.doj.aopapp.service.*.*(..))" id="logForAllMethods"/>

#2. In Second pointcut expression, we have declared after throwing advice, it is valid for all public methods whose name is transfer() with taking three arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

<aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>

Spring AOP Around Advice Example
Let’s create an example for a Around advice, using xml configuration using <aop:around/> namespace.

Spring AOP Maven Dependencies

<properties>
   <spring.version>4.3.7.RELEASE</spring.version>
   <aspectj.version>1.8.9</aspectj.version>
  </properties>
  
  <dependencies>
   <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring.version}</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context-support</artifactId>
         <version>${spring.version}</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aop</artifactId>
         <version>${spring.version}</version>
     </dependency>
     
     <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjrt</artifactId>
          <version>${aspectj.version}</version>
      </dependency>
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>${aspectj.version}</version>
      </dependency>
  </dependencies>

ApplicationContext Configuration file based on XML Config
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <aop:config>
  <aop:aspect ref="loggingAspect">
   <!-- all public methods with any arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
   <aop:pointcut expression="execution(* com.doj.aopapp.service.*.*(..))" id="logForAllMethods"/>
   <!-- all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
   <aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>
   <aop:around method="aroundAdviceForAllMethods" pointcut-ref="logForAllMethods"/>
   <aop:around method="aroundAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
 </aop:config>
 
 <bean id="transferService" class="com.doj.aopapp.service.TransferServiceImpl"/>
 
 <bean id="loggingAspect" class="com.doj.aopapp.aspect.LoggingAspect"/>
</beans>


Aspect class “LoggingAspect”:
Write aspect class and methods to be executed as advice.
LoggingAspect.java

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;

/**
 * @author Dinesh.Rajput
 *
 */
public class LoggingAspect {
 
 /**
  * Declaring around advice 
  * @param jp
  * @throws Throwable
  */
 public void aroundAdviceForAllMethods(ProceedingJoinPoint jp) throws Throwable {
  System.out.println("****Before advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForAllMethods()");
        jp.proceed();
        System.out.println("****After advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForAllMethods()" );
        System.out.println();
    }
 
 /**
  * Declaring around advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 public void aroundAdviceForTransferMethods(ProceedingJoinPoint jp) throws Throwable {
  System.out.println("****Before advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForTransferMethods()");
        jp.proceed();
        System.out.println("****After advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForTransferMethods()" );
        System.out.println();
    }
 
 /**
  * Declaring named pointcut
  */
 @Pointcut("execution(* com.doj.aopapp.service.*.*(..))")
 public void logForAllMethods(){}
}

The advice method will have a method argument of type ProceedingJoinPoint which can be used call advised method.

Target method of Service class on which aspects needs to apply

TransferService.java

/**
 * 
 */
package com.doj.aopapp.service;

/**
 * @author Dinesh.Rajput
 *    
 */
public interface TransferService {
 
 void transfer(String accountA, String accountB, Long amount);
 
 Double checkBalance(String account);
 
 Long withdrawal(String account, Long amount);
 
 void diposite(String account, Long amount);
}

TransferServiceImpl.java

/**
 * 
 */
package com.doj.aopapp.service;

/**
 * @author Dinesh.Rajput
 *
 */
public class TransferServiceImpl implements TransferService {
 
 @Override
 public Double checkBalance(String account) {
  System.out.println("Available balance: 50000");
  return new Double(50000);
 }
 
 @Override
 public void transfer(String accountA, String accountB, Long amount) {
  System.out.println(amount+" Amount trasferring from "+accountA+" to "+accountB);
 }

 @Override
 public Long withdrawal(String account, Long amount) {
  System.out.println("Withdrawal amount: " +amount);
  return amount;
 }

 @Override
 public void diposite(String account, Long amount) {
  System.out.println(amount+" Amount has been diposited to "+account);
 }

}

Test Class for Spring AOP Around Advice Configuration and Execution
Let’s execute following test class and analyse the output on the console.

/**
 * 
 */
package com.doj.aopapp.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.doj.aopapp.service.TransferService;

/**
 * @author Dinesh.Rajput
 *
 */
public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  TransferService transferService = applicationContext.getBean(TransferService.class);
  transferService.transfer("accountA", "accountB", 50000l);
  transferService.checkBalance("accountA");
  transferService.diposite("accountA",  50000l);
  transferService.withdrawal("accountB", 40000l);
  applicationContext.close();
 }

}

Output on the Console:

Mar 10, 2017 12:35:29 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@179d3b25: startup date [Fri Mar 10 00:35:29 IST 2017]; root of context hierarchy
Mar 10, 2017 12:35:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
****Before advised method execution transfer LoggingAspect.aroundAdviceForAllMethods()
****Before advised method execution transfer LoggingAspect.aroundAdviceForTransferMethods()
50000 Amount trasferring from accountA to accountB
****After advised method execution transfer LoggingAspect.aroundAdviceForTransferMethods()

****After advised method execution transfer LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution checkBalance LoggingAspect.aroundAdviceForAllMethods()
Available balance: 50000
****After advised method execution checkBalance LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution diposite LoggingAspect.aroundAdviceForAllMethods()
50000 Amount has been diposited to accountA
****After advised method execution diposite LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution withdrawal LoggingAspect.aroundAdviceForAllMethods()
Withdrawal amount: 40000
****After advised method execution withdrawal LoggingAspect.aroundAdviceForAllMethods()

Mar 10, 2017 12:35:30 AM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@179d3b25: startup date [Fri Mar 10 00:35:29 IST 2017]; root of context hierarchy

As output of above console, every log messages has been executed before and after advised method execution.

Project Structure

Spring AOP Around Advice Example using XML Config

Spring AOP Related Posts

  1. Spring AOP Interview Questions and Answers
  2. Spring AOP Tutorial- Aspect Oriented Programming with Spring
  3. @Aspect Annotation in Spring
  4. Advices in Spring AOP
  5. Spring AOP JoinPoints and Advice Arguments
  6. Spring AOP Pointcuts and Wildcard Expressions
  7. Spring AOP XML configuration
  8. Spring AOP XML Schema based Example
  9. Spring AOP AspectJ @Before Annotation Advice Example
  10. Spring AOP Before Advice Example using XML Config
  11. Spring AOP AspectJ @After Annotation Advice Example
  12. Spring AOP After Advice Example using XML Config
  13. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  14. Spring AOP After-Returning Advice Example using XML Config
  15. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  16. Spring AOP After Throwing Advice Example using XML Config
  17. Spring AOP AspectJ @Around Annotation Advice Example
  18. Spring AOP Writing First AspectJ Program in Spring
  19. Spring AOP Proxies in Spring
  20. Spring AOP Transaction Management in Hibernate
  21. Spring Transaction Management
  22. Spring Declarative Transaction Management Example

Spring AOP AspectJ @Around Annotation Advice Example

In this spring aop Around advice example, we will learn how to use aspectj @Around annotation with java configuration. In Spring AOP, Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception i.e a method which annotated with AspectJ @Around annotation run before and after any matching pointcut expression, advised method execution.

Download Application Source Code

Spring AOP AspectJ @Around Annotation Advice Example from GitHub.

Let’s create a simple spring application and add logging aspect to be invoked every joint point in the service class in the application. This example is also available with XML configuration in the application Spring AOP Around Advice Example.

AspectJ @Around Annotation
@Around annotation is an Aspectj annotation, it is not Spring AOP annotation, so we have to add Aspectj maven dependency with Spring AOP in this example. Let’s see our LoggingAspect class with Around advice annotation.

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class LoggingAspect {
 
 /**
  * Declaring around advice 
  * @param jp
  * @throws Throwable
  */
 //@Around("execution(* com.doj.aopapp.service.*.*(..))") // around advice with pointcut expression directly
 @Around("logForAllMethods()") //around advice with name pointcut that declared as name logForAllMethods()
 public void aroundAdviceForAllMethods(ProceedingJoinPoint jp) throws Throwable {
  System.out.println("****Before advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForAllMethods()");
        jp.proceed();
        System.out.println("****After advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForAllMethods()" );
        System.out.println();
    }
 
 /**
  * Declaring around advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @Around("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void aroundAdviceForTransferMethods(ProceedingJoinPoint jp) throws Throwable {
  System.out.println("****Before advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForTransferMethods()");
        jp.proceed();
        System.out.println("****After advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForTransferMethods()" );
        System.out.println();
    }
 
 /**
  * Declaring named pointcut
  */
 @Pointcut("execution(* com.doj.aopapp.service.*.*(..))")
 public void logForAllMethods(){}
}

Note: Around advice is special type of advice in the Spring AOP and it has capacity to modify the return of advised method and has full to invoke advised method. And never forget to use ProceedingJoinPoint as parameter and must call ProceedingJoinPoint.proceed(); method, else the advised method will never be executed.

Declare Pointcut expressions
#1. In this expression, We have declared around advice, it is valid for all public methods with any number arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

@Around("execution(* com.doj.aopapp.service.*.*(..))")

#2. In this expression, We have declared around advice, it is valid for all public methods whose name is transfer() with taking three arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

@Around("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")

Spring AOP AspectJ @Around Annotation Example
Now let’s see complete example of Spring AOP aspectj @Around annotation.

Spring AOP and AspectJ Maven Dependencies

<properties>
   <spring.version>4.3.7.RELEASE</spring.version>
   <aspectj.version>1.8.9</aspectj.version>
  </properties>
  
  <dependencies>
   <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring.version}</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context-support</artifactId>
         <version>${spring.version}</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aop</artifactId>
         <version>${spring.version}</version>
     </dependency>
     
     <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjrt</artifactId>
          <version>${aspectj.version}</version>
      </dependency>
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>${aspectj.version}</version>
      </dependency>
  </dependencies>

ApplicationContext Configuration file based on Java Config
AppConfig.java

/**
 * 
 */
package com.doj.aopapp.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages={"com.doj.aopapp.aspect", "com.doj.aopapp.service"})
public class AppConfig {
 
}

#1. Enabling @AspectJ using @EnableAspectJAutoProxy Annotation:
Spring AOP provides an annotation to enable @AspectJ support in the application. By default spring framework doesn’t create any proxy for any advice, so we have to enable by using @EnableAspectJAutoProxy annotation.

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

}

#2. Enabling @AspectJ using <aop:aspectj-autoproxy/> in XML Configuration:
<aop:aspectj-autoproxy/> namespace is equivalent to @EnableAspectJAutoProxy annotation to enable @AspectJ support in the application in XML configuration. Let’s see how to use this namespace <aop:aspectj-autoproxy/>.

<!-- Enable @AspectJ annotation support  -->
    <aop:aspectj-autoproxy/>

Target method of Service class on which aspects needs to apply

TransferService.java

/**
 * 
 */
package com.doj.aopapp.service;

/**
 * @author Dinesh.Rajput
 *    
 */
public interface TransferService {
 
 void transfer(String accountA, String accountB, Long amount);
 
 Double checkBalance(String account);
 
 Long withdrawal(String account, Long amount);
 
 void diposite(String account, Long amount);
}

TransferServiceImpl.java

/**
 * 
 */
package com.doj.aopapp.service;

import org.springframework.stereotype.Service;

/**
 * @author Dinesh.Rajput
 *
 */
@Service
public class TransferServiceImpl implements TransferService {

 @Override
 public void transfer(String accountA, String accountB, Long amount) {
  System.out.println(amount+" Amount trasferring from "+accountA+" to "+accountB);
 }

 @Override
 public Double checkBalance(String account) {
  System.out.println("Available balance: 50000");
  return new Double(50000);
 }

 @Override
 public Long withdrawal(String account, Long amount) {
  System.out.println("Withdrawal amount: " +amount);
  return amount;
 }

 @Override
 public void diposite(String account, Long amount) {
  System.out.println(amount+" Amount has been diposited to "+account);
 }

}

Aspect class:
LoggingAspect.java as given above in this tutorial.

Test Class for Spring AspectJ Configuration and Execution

Let’s execute following test class and analyse the output on the console.

/**
 * 
 */
package com.doj.aopapp.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.doj.aopapp.config.AppConfig;
import com.doj.aopapp.service.TransferService;

/**
 * @author Dinesh.Rajput
 *
 */
public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
  TransferService transferService = applicationContext.getBean(TransferService.class);
  transferService.checkBalance("accountA");
  transferService.transfer("accountA", "accountB", 50000l);
  transferService.diposite("accountA",  50000l);
  transferService.withdrawal("accountB", 40000l);
  applicationContext.close();
 }

}

Output on the Console:

Mar 09, 2017 11:49:10 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Thu Mar 09 23:49:10 IST 2017]; root of context hierarchy
****Before advised method execution checkBalance LoggingAspect.aroundAdviceForAllMethods()
Available balance: 50000
****After advised method execution checkBalance LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution transfer LoggingAspect.aroundAdviceForAllMethods()
****Before advised method execution transfer LoggingAspect.aroundAdviceForTransferMethods()
50000 Amount trasferring from accountA to accountB
****After advised method execution transfer LoggingAspect.aroundAdviceForTransferMethods()

****After advised method execution transfer LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution diposite LoggingAspect.aroundAdviceForAllMethods()
50000 Amount has been diposited to accountA
****After advised method execution diposite LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution withdrawal LoggingAspect.aroundAdviceForAllMethods()
Withdrawal amount: 40000
****After advised method execution withdrawal LoggingAspect.aroundAdviceForAllMethods()

Mar 09, 2017 11:49:10 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Thu Mar 09 23:49:10 IST 2017]; root of context hierarchy

As output of above console, every log messages has been executed before and after advised method execution.

Project Structure

Spring AOP AspectJ @Around Annotation Advice Example

Spring AOP Related Posts

  1. Spring AOP Interview Questions and Answers
  2. Spring AOP-Introduction to Aspect Oriented Programming
  3. @Aspect Annotation in Spring
  4. Advices in Spring AOP
  5. Spring AOP JoinPoints and Advice Arguments
  6. Spring AOP-Declaring pointcut Expressions with Examples
  7. Spring AOP XML configuration
  8. Spring AOP XML Schema based Example
  9. Spring AOP AspectJ @Before Annotation Advice Example
  10. Spring AOP Before Advice Example using XML Config
  11. Spring AOP AspectJ @After Annotation Advice Example
  12. Spring AOP After Advice Example using XML Config
  13. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  14. Spring AOP After-Returning Advice Example using XML Config
  15. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  16. Spring AOP After Throwing Advice Example using XML Config
  17. Spring AOP Around Advice Example using XML Config
  18. Spring AOP Writing First AspectJ Program in Spring
  19. Spring AOP Proxies in Spring
  20. Spring AOP Transaction Management in Hibernate
  21. Spring Transaction Management
  22. Spring Declarative Transaction Management Example
  23. Spring AOP-Ordering of Aspects with Example