Friday, January 29, 2021

Spring MVC XML as Response Example

In this post we’ll see how to get XML as response in Spring MVC application. For marshalling and unmarshalling (converting object from/to XML) JAXB is used in this Spring MVC example.

Technologies used

Following is the list of tools used for the Spring MVC XML generation example.

  • Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  • Java 10
  • Tomcat server V 9.0.10
  • Eclipse IDE
  • JAXB API 2.3.0

Spring MVC Project structure using Maven

Maven Dependencies

Apart from Spring dependencies JAXB dependencies are also to be added to the pom.xml for generation of XML. From JDK 9, JEE modules are deprecated so you will need to add dependencies in your pom.xml for inclusion of JAXB jars previously these jars were part of JDK itself.

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>javax.activation</groupId>
  <artifactId>javax.activation-api</artifactId>
  <version>1.2.0</version>
</dependency>

Requirement for generating XML in Spring MVC

In order to return XML as response with in your Spring MVC application-

  1. You need to annotate your model bean with JAXB annotations.
  2. @ResponseBody annotation has to be added to the controller's method, with that returned object is serialized to the response body through an HttpMessageConverter.

Spring MVC generate XML as response – Model classes

There are two classes User class whose objects are returned in the XML form and UserListContainer class which contains the List of objects of type User, this class is needed as we are sending a list of Users. These POJOs are annotated with JAXB annotations for defining the XML structure.

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement
@XmlType(propOrder = {"firstName", "lastName", "email"})
public class User {

 private String firstName;
 private String lastName;
 private String email;

 public User() {
  
 }
 public User(String firstName, String lastName, String email) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
 }
 
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
}
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="users")
public class UserListContainer {
  private List<User> userList;

  @XmlElement(name = "user")
  public List<User> getUserList() {
    return userList;
  }

  public void setUserList(List<User> userList) {
    this.userList = userList;
  }
}

Spring MVC XML as response – Controller class

@Controller
public class UserController {
  @RequestMapping(value = "/getUsers", method = RequestMethod.GET, produces="application/xml")
  @ResponseBody
  public UserListContainer getUsers(Model model) throws Exception{
    List<User> users = getListOfUsers();
    UserListContainer userList = new UserListContainer();
    userList.setUserList(users);
    return userList;
  }
    
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() throws ParseException {
    List<User> users = new ArrayList<User>();
    users.add(new User("Jack", "Reacher", "abc@xyz.com"));
    users.add(new User("Remington", "Steele", "rs@cbd.com"));
    users.add(new User("Jonathan", "Raven", "jr@sn.com"));
    return users;
  }
}

Here in the handler method you can see a new attribute “produces” with value as “application/xml” with in the @RequestMapping annotation to explicitly specify the MIME media types or representations a resource can produce and send back to the client.

@ResponseBody annotation is also used in the handler method to indicate that the returned object has to be serialized to the response body. Note that return is serialized to the response body through an HttpMessageConverter.

Deploying and testing application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/getUsers and XML will be returned as response.

Spring MVC XML generation

That's all for this topic Spring MVC XML as Response Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Excel Generation Example
  2. Difference Between @Controller And @RestController Annotations in Spring
  3. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  4. Spring MVC - Binding List of Objects Example
  5. Spring MVC Form Example With Bean Validation

You may also like-

  1. Spring Transaction Attributes - Propagation And Isolation Level Settings
  2. Configuring DataSource in Spring Framework
  3. Bean Scopes in Spring With Examples
  4. Spring Expression Language (SpEL) With Examples
  5. Difference Between ArrayList And LinkedList in Java
  6. Java ReentrantLock With Examples
  7. Try-With-Resources in Java With Examples
  8. Zipping Files And Folders in Java

Thursday, January 28, 2021

Spring MVC JSON as Response Example

In this post we’ll see how to generate JSON as response in Spring MVC application.

Technologies used

Following is the list of tools used for the Spring MVC JSON generation example.

  • Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  • Java 10
  • Tomcat server V 9.0.10
  • Eclipse Photon 4.8.0 for Java EE development (This Eclipse version supports Java 10)
  • Jackson library (For JSON)

Spring MVC Project structure using Maven

Maven Dependencies

Apart from Spring framework dependencies you need to add the following dependency for JSON.

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

Which adds the following jars.

jackson-databind-2.9.6.jar
jackson-annotations-2.9.0.jar
jackson-core-2.9.6.jar

Wednesday, January 27, 2021

Spring MVC Excel Generation Example

In this post we’ll see how to generate an Excel sheet in Spring MVC using the fields from a view page (JSP).

Technologies used

Following is the list of tools used for the Spring MVC Excel generation example.

  • Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  • Java 10
  • Tomcat server V 9.0.10
  • Eclipse IDE
  • Apache POI 4.0.0 (Required for generating excel)

Spring framework support for Apache POI

Apache POI is an open source library using which you can read and write Excel files from your Java program.

Spring framework provides support for Excel document views using two abstract classes-

  1. AbstractXlsView- You will use AbstractXlsView as superclass for Excel document views in traditional XLS format.
  2. AbstractXlsxView- You will use AbstractXlsxView as superclass for Excel document views in the Office 2007 XLSX format.

Both of these classes are compatible with Apache POI 3.5 and higher.

With in Apache POI also there are two implementations for these two types of sheets-

  1. HSSF- It is the POI Project's pure Java implementation of the Excel '97(-2007) (.xls) file format.
  2. XSSF- It is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.

Spring MVC PDF Generation Example

In this post we’ll see how to generate a PDF in Spring MVC using the fields from a view page (JSP).

Technologies used

Following is the list of tools used for the Spring MVC PDF generation example.

  • Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  • Java 10
  • Tomcat server V 9.0.10
  • Eclipse Photon 4.8.0 for Java EE development
  • iText 7.1.3
  • OpenPDF 1.2.3

Options for generating PDF in Spring MVC

  1. One of the option for generating PDF is iText. In Spring framework iText support is for a very old version so requires some work on your behalf to get it working with the current versions.
  2. Another option is OpenPDF which is a fork from iText. Spring framework class AbstractPdfView can directly be used to generate PDF using OpenPDF. Spring framework recommends OpenPDF.
    Reference- https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/view/document/AbstractPdfView.html

Tuesday, January 26, 2021

Spring MVC File Download Example

In this post we’ll see a Spring MVC application to download a file (image, pdf, zip etc.) from web server.

Spring MVC file download example – Technologies used

Following is the list of tools used for the Spring MVC file download example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. Tomcat server V 9.0.10
  4. Eclipse Photon 4.8.0 for Java EE development.

Spring MVC file download example project structure using Maven

Options in Spring MVC for file download

  • In your Spring MVC application for file download you can use HttpServletResponse to write the downloaded file to the output stream of the servlet response. If you are using this option then you need to do the following.

Monday, January 25, 2021

Spring MVC File Upload (Multipart Request) Example

In this post we’ll see a Spring MVC file upload example for single and multiple files.

Following is the list of tools used for the Spring MVC file upload example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. commons-fileupload 1.3.3 (If using Apache Commons file upload)
  4. Tomcat server V 9.0.10
  5. Eclipse Photon 4.8.0 for Java EE development

Sunday, January 24, 2021

Spring MVC Redirect Example

In this post we’ll see a Spring MVC page redirect example with redirect to URL with parameters.

Spring MVC Project structure using Maven

Spring MVC page redirect example

In this example there is a form where user data is entered. On submitting the form the form data is saved and then using the user ID there is a redirect to a URL where userId is passed as parameter- “/showUser/" +userId where using that userId a User object is created.

This is the handler method in the controller class, where redirect is used to transfer to another page.

@RequestMapping(value = "/saveUser", method = RequestMethod.GET)
public String saveUser(@ModelAttribute("user") User user, Model model) {
 String userId = saveUser(user);
 // redirecting
 return "redirect:/showUser/" +userId;
}

This is the handler method which handles the request path which is created using the Spring MVC redirect.

@RequestMapping(value = "/showUser/{userId}", method = RequestMethod.GET)
public String showUser(@PathVariable("userId") String userId, Model model) {
 model.addAttribute("User", findUserById(userId));
 return "user"; 
}

Spring MVC page redirect example - Views

There are three JSPs used in this page rediredt example.

home.jsp

This is the JSP page with a link to registration form page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - Home JSP</title>
</head>
<body>
  <div>${message}</div>
  <a href='<s:url value="/registerUser"></s:url>'>Register User</a>
</body>
</html>

userRegister.jsp

This is the registration form page which is opened after clicking the “Register User” link. Once this page is submitted the user data is saved and then the page is redirected to show the user details for the saved User. Note that in the handler method @PathVariable annotation is used to retrieve the parameter from the request path.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Registration</title>
</head>
<body>
  <form:form action="saveUser" modelAttribute="user" method="GET">
    <table>
      <tr>
        <td>
          <form:label path="firstName">First Name</form:label>
        </td>
        <td>
          <form:input path="firstName" id="firstname" />
        </td>
      </tr>
      <tr>
        <td>
          <form:label path="lastName">Last Name</form:label>
        </td>
        <td>
          <form:input path="lastName" id="lastname" />
        </td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit"></td>
      </tr>
    </table>
  </form:form>
</body>
</html>

user.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC tutorial - User</title>
</head>
<body>

<h4>User ID</h4><span>${User.userId}</span>
<h4>First Name</h4><span>${User.firstName}</span>
<h4>Last Name</h4><span>${User.lastName}</span>
</body>
</html>

Spring MVC page redirect example - Controller class

Here is the complete Controller class.

@Controller
public class MessageController {
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String showHome(Model model) {
  model.addAttribute(new User());
  model.addAttribute("message", "Spring MVC redirect example");
  return "home";
 }
 
 @RequestMapping(value = "/registerUser", method = RequestMethod.GET)
 public String showUserRegForm(@ModelAttribute("user") User user, Model model) {
  model.addAttribute("User", user);
  return "userRegister";
 }
 
 @RequestMapping(value = "/saveUser", method = RequestMethod.GET)
 public String saveUser(@ModelAttribute("user") User user, Model model) {
  String userId = saveUser(user);
  // redirecting
  return "redirect:/showUser/" +userId;
 }
 
 @RequestMapping(value = "/showUser/{userId}", method = RequestMethod.GET)
 public String showUser(@PathVariable("userId") String userId, Model model) {
  model.addAttribute("User", findUserById(userId));
  return "user"; 
 }
 
 // Dummy method to save user
 private String saveUser(User user) {
  System.out.println("Saving User");
  return "101";
 }
 // Dummy method to find user
 private User findUserById(String userId) {
  System.out.println("User ID " + userId);
  User user = new User();
  user.setUserId(userId);
  user.setFirstName("Leonard");
  user.setLastName("Nimoy");
  return user;
 }
}

That's all for this topic Spring MVC Redirect Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC @RequestParam Annotation Example
  2. Spring MVC Form Example With Bean Validation
  3. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  4. Spring JdbcTemplate Select Query Example
  5. @Resource Annotation in Spring Autowiring

You may also like-

  1. Excluding Bean From Autowiring in Spring
  2. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  3. Transaction Management in Spring
  4. Internationalization (i18n) Using MessageSource in Spring
  5. Java Collections Interview Questions And Answers
  6. Switch Case Statement in Java With Examples
  7. Primitive Type Streams in Java Stream API
  8. Converting String to Enum Type in Java

Friday, January 22, 2021

Java ScheduledThreadPoolExecutor - Task Scheduling in Java

Java executors framework provides an alternative to manage threads rather than using the Thread class. At the core of the executors is the Executor interface, which is extended by ExecutorService and ScheduledExecutorService interfaces. There are also pre defined executor classes that implement these interfaces like ThreadPoolExecutor class which executes the submitted task using one of the pooled thread. ThreadPoolExecutor class executes the submitted task as soon as the thread is available. If you want to schedule tasks to run after a given delay, or to execute periodically as per the configured schedule then you can use ScheduledThreadPoolExecutor class in Java.

ScheduledThreadPoolExecutor in Java

ScheduledThreadPoolExecutor class is part of the executors framework. This class extends ThreadPoolExecutor and implements ScheduledExecutorService interface. ScheduledExecutorService interface extends ExecutorService interface and provides methods for scheduling.

Thursday, January 21, 2021

Java ThreadPoolExecutor - Thread Pooling With ExecutorService

ThreadPoolExecutor class in Java implements both Executor and ExecutorService interfaces and is part of java.util.concurrent package. ThreadPoolExecutor is used to create and manage thread pools and it executes each submitted task using one of possibly several pooled threads.

Using thread pools in Java provide benefits in following ways-

  1. You may see improvement in performance when executing large numbers of asynchronous tasks as overhead of creating thread per task is not there, threads are taken from the maintained thread pool instead.
  2. Thread pools also provide means of managing the resources (by restricting the pool size, having an option to keep thread alive for the given time) consumed when executing a collection of tasks.
  3. ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

Sunday, January 17, 2021

Spring MVC Pagination Example Using PagedListHolder

In this post we’ll see a Spring MVC pagination example using the PagedListHolder class.

Technologies used

Following is the list of tools used for the Spring MVC pagination example.

  1. Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  2. Java 10
  3. Tomcat server V 9.0.10
  4. Eclipse IDE

Saturday, January 16, 2021

Polymorphism in Python

Polymorphism is one of the four fundamental OOPS concepts. The other three being Inheritance, Encapsulation, Abstraction

Polymorphism is a Greek word where poly means many and morph means change thus it refers to the ability of an entity taking many forms. In an object oriented context that means an entity which may be a method, object or operator can represent different types based on the scenario where they are used.

Polymorphism in Python

In an object oriented language you will find support for Polymorphism through-

  • Method overloading
  • Method overriding
  • Operator overloading

Python being an object oriented language also supports Polymorphism but only through Method overriding and operator overloading. Method overloading in its traditional sense is not supported in Python.

Friday, January 15, 2021

Python Generator, Generator Expression, Yield Statement

In this article we’ll learn about generators in Python and how and why to use them.

The three things that you need to understand to master generators are-

  1. Generator functions itself.
  2. Generator expressions.
  3. Python yield statement

Python generator

Generator is a function which returns a generator iterator, where generator iterator is an object that can be iterated.

A generator function in Python looks like a normal function except that it contains yield statement rather than return (it may contain return too but yield statement is must to be qualified as a generator function).

Using yield statement generator generates a value that can be used in a for-loop or that can be retrieved one at a time with the next() function.

Thursday, January 14, 2021

Keyword Arguments in Python

Generally if you have a function with parameters, while calling the function you pass the arguments in the same positional order. There is also an option of keyword arguments in Python where arguments are passed as key, value pair, since the parameters are identified by their names so keyword arguments are also known as named arguments.

For example here is a function where the positional arguments are passed.

def display_amount(message, amount):
  print(message, '%.2f ' % amount)

display_amount("Total Amount is", 50.56)

Same function with keyword arguments can be written as-

def display_amount(message, amount):
  print(message, '%.2f ' % amount)

display_amount(message="Total Amount is", amount=50.56)

Default Arguments in Python

In Python, function arguments can have default value. If a function, that already has a default value, is called without the argument then the default value is used otherwise the passed value overrides the default value.

Default arguments in Python function example

In the function display_message() one of the argument has a default value. While calling the function you can chose not to pass that argument, in that case default value is used.

def display_message(name, msg='Hi '):
  print(msg + name)

display_message("Tom")

Output

Hi Tom

Wednesday, January 13, 2021

Functions in Python With Examples

In this post we’ll see what are functions, what are the advantages of creating functions, how to define functions in Python and how to execute functions in Python and return result, if any.

What are functions

A function is a block of code that is usually written to perform a specific functionality. A function is executed only when you call it and you can pass data to a function (known as function parameters) and return a result from a function.

Advantages of using functions

  1. Functions help you in writing modular code as you can write different functions for different functionality. So. Functions help you in dividing application into smaller chunks.
  2. Functions help in making your code reusable as you can call functions when required and use them in different applications too.
  3. Functions also avoid repetition of code as the functionality which is required at several places can be written as a separate function and that function can be called as and when required.
  4. Functions make your code easy to maintain as any extra functionality can be written as an extra function without disturbing the existing code base.
  5. Functions make it easy to debug code, since different functions are written for different tasks so it easy to pin-point which function has a problem.

Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python

In this article we’ll see what are variable length arguments (*args) in Python and what are keyword variable length arguments (**kwargs) in Python.


Variable length arguments in Python

A variable length argument as the name suggests is an argument that can accept variable number of values. To indicate that the function can take variable number of argument you write a variable argument using a ‘*’, for example *args.

Tuesday, January 12, 2021

Angular HttpClient - Set Response Type as Text

In this tutorial we’ll see how to set response type as text when using Angular HttpClient to make a Http request.

Requesting a types response – Angular HttpClient

HttpClient supports HTTP methods such as PUT, POST, and DELETE, which you can use to modify the remote data and get method to fetch data from a server. With each of these methods you can send options object as an argument that you can use to configure the request. In that object you can set values as key, value pairs and it gives you an option to set HttpHeaders, HttpParams, responseType and other values.

ResponseType options value which you can set are arraybuffer, blob, text, json. Default for response type is {responseType: 'json'}.

Setting response type as text example

In this example we’ll see how to set response type as text while sending HttpClient request to the spring rest API.

In the Spring Boot application we have a Rest Controller class with handler mappings for different CRUD operations. DB used is MySQL and the DB table is User.

To get more details and code for the Spring Boot CRUD application, refer this post- Spring Boot REST API CRUD Example With Spring Data JPA

Monday, January 11, 2021

Python Functions: Returning Multiple Values

In Python a function can return multiple values, that is one of the difference you will find in a Python function and function (or method) in a language like C or Java.

Returning multiple values in Python

If you want to return multiple values from a function you can use return statement along with comma separated values. For example-

return x, y, z

When multiple values are returned like this, function in Python returns them as a tuple. When assigning these returned values to a variable you can assign them to variables in sequential order or in a tuple. Let’s try to clarify it with examples.

Sunday, January 10, 2021

Thread Priority in Java Multi-Threading

When we talk about thread we use terms like concurrent threads or threads executing concurrently. But in reality threads also run one at a time (at least in a single CPU system), threads are given CPU cycle in a time shared manner to simulate concurrency. The order in which multiple threads will be executed is decided by thread scheduler and thread priority is used by the thread scheduler to make that decision. This article is about the thread priorities available in Java multi-threading and how to get and set Java thread priority.

Java Thread Priority

When a thread is created in Java, it inherits its priority from the thread that creates it. Thread's priority can be modified at any time after its creation using the setPriority() method which is a member of Thread class.

Saturday, January 9, 2021

Inheritance in Java

Inheritance is one of the four fundamental OOP concepts. The other three being- Encapsulation, Polymorphism, Abstraction.


Inheritance Concept

Inheritance is a mechanism, by which one class acquires, all the properties and behaviors of another class. The class whose members are inherited is called the Super class (or base class), and the class that inherits those members is called the Sub class (or derived class).

The relationship between the Super and inherited subclasses is known as IS-A relationship.

As Example- If Shape is a super class and there are subclasses Circle and Rectangle derived from the Shape super class then Circle IS-A Shape and Rectangle IS-A shape.

Polymorphism in Java

Polymorphism is one of the four fundamental OOPS concepts. The other three are Inheritance, Encapsulation, Abstraction. In this post we'll see examples of Polymorphism in Java.


Polymorphism Concept

Polymorphism, a Greek word, where poly means many and morph means change, refers to the ability of an object taking many forms.

The concept of polymorphism is often expressed as "One interface, multiple methods". Where one general class may have the generic method and the derived classes (classes which extend the general class) may add class specific implementation to that method. At the time of execution "One interface" i.e. the general class will take "many forms" i.e. references of the derived classes (See example to have clarity).

Friday, January 8, 2021

Abstraction in Java

Abstraction is one of the four fundamental OOP concepts. The other three being- Inheritance, Polymorphism, Encapsulation

Abstraction Concept

Abstraction means hiding the complexity and only showing the essential features of the object. So in a way, abstraction means abstracting/hiding the real working (implementation details) and we, as a user, knowing only how to use it.

Real world example of abstraction would be-

  • A vehicle which we drive with out caring or knowing what all is going underneath.
  • A TV set where we enjoy programs with out knowing the inner details of how TV works.

An example of abstraction in Java is- Java Database Connectivity (JDBC) API which provides universal data access from the Java programming language. Using the JDBC API, we can access virtually any data source without knowing how the driver for that particular data source is implemented. All we have is an API with a given set of methods.

Encapsulation in Java

Encapsulation is one of the four fundamental OOP concepts. The other three are- Inheritance, Polymorphism, Abstraction


What is Encapsulation

The concept of Encapsulation is to keep together the implementation (code) and the data it manipulates (variables). Having proper encapsulation ensures that the code and data both are safe from misuse by outside entity.

Encapsulation also helps in maintaining code as the implementation that may change and evolve is kept at one place which makes it easy to change with out impacting other classes in application.

Wednesday, January 6, 2021

How to Remove Duplicate Elements From an ArrayList in Java

ArrayList in Java allows adding duplicate elements but sometimes there may be a need to remove duplicates from a list. In this post we'll talk about the ways to remove duplicate elements from an ArrayList in Java. Options you have are as follows.

  • There is a brute force approach where you create a new list and loop through the already created old list, use contains() method to see if element is already added to the new list if not add it to the new list otherwise discard it. That way you can remove all duplicate elements from ArrayList without using any other collection. See example.
  • You can simply use a HashSet, since HashSet stores only unique elements you can use that feature of HashSet to remove duplicate elements from a list. Only problem is it won't retain the order of the list. See example.
  • If you want order of the List to be retained you can use LinkedHashSet which maintains the insertion order. See example.
  • Java 8 onward you can use Stream API which provides a very simple way to remove duplicate elements from ArrayList. See example.

Let's see examples of all these options one by one.

Read Also: Java Collections Framework

Removing duplicates from ArrayList without using any API or other Collection

public class RemoveDuplicatesDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
    List<String> newList = new ArrayList<>();
    for(String name : cityList){
      if(!newList.contains(name)){
        newList.add(name);
      }
    }

    for(String name : newList){
      System.out.println("City Name - " + name);
    }
  }
}

Using HashSet to remove duplicate elements from ArrayList

You can create a new HashSet by passing the List as argument. Any duplicates in the ArrayList would be discarded as HashSet stores only unique elements. Then you can add the Set again to the List after clearing the List. That gives you the List without any duplicates.

public class RemoveDuplicatesDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
    // creating a hashset using the list
    Set<String> citySet = new HashSet<String>(cityList);
    // remove all the elements from the list 
    cityList.clear();
    // add all the elements of the set to create a
    // list with out duplicates
    cityList.addAll(citySet);
    
    // displaying the elements
    for(String name : cityList){
      System.out.println("City Name - " + name);
    }
  }
}

Output

City Name - Delhi
City Name - Chennai
City Name - Kolkata
City Name - Mumbai
City Name - Bangalore

It can be seen that duplicate elements from the ArrayList are removed but the original order is not retained. Though in most of the cases when we have such requirement to remove duplicates from the list order doesn't matter but if it does sweat not! LinkedHashSet is there to retain the order. LinkedHashSet differ from HashSet in that it maintains the insertion order.

Using LinkedHashSet to remove duplicate elements from ArrayList

Here is an example using LinkedHashSet to remove duplicate elements from an ArrayList, insertion order would be retained by using this option.

public class RemoveDuplicatesDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // creating a linkedhashset using the list
    Set<String> citySet = new LinkedHashSet<String>(cityList);
    // remove all the elements from the list 
    cityList.clear();
    // add all the elements of the set to create a
    // list with out duplicates
    cityList.addAll(citySet);
    
    // displaying the elements
    for(String name : cityList){
      System.out.println("City Name - " + name);
    }
  }
}

Output

City Name - Delhi
City Name - Mumbai
City Name - Bangalore
City Name - Chennai
City Name - Kolkata

It can be seen that the order is retained now.

Removing duplicates from ArrayList using Java Streams

Stream API in Java provides a very simple way to remove duplicate elements from ArrayList using the distinct method. Note that this option is available Java 8 onward.

public class RemoveDuplicatesDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    
    cityList = cityList.stream().distinct().collect(Collectors.toList());
          
    // displaying the elements
    for(String name : cityList){
      System.out.println("City Name - " + name);
    }
  }
}

Output

City Name - Delhi
City Name - Mumbai
City Name - Bangalore
City Name - Chennai
City Name - Kolkata

It can be seen that the duplicate element is removed from the ArrayList and original order is retained too and all that is done in a single line.

That's all for this topic How to Remove Duplicate Elements From an ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Remove Elements From an ArrayList in Java
  2. How ArrayList Works Internally in Java
  3. How and Why to Synchronize ArrayList in Java
  4. Difference Between ArrayList And CopyOnWriteArrayList in Java
  5. Java Collections Interview Questions And Answers

You may also like -

  1. How HashMap Works Internally in Java
  2. Difference Between Comparable and Comparator in Java
  3. Marker interface in Java
  4. Why Class Name And File Name Should be Same in Java
  5. Functional Interfaces in Java
  6. Race Condition in Java Multi-Threading
  7. Object Cloning in Java
  8. SerialVersionUID And Versioning in Java Serialization

Tuesday, January 5, 2021

Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class

Why wait(), notify() and notifyAll() methods are in Object class and not in Thread class is one of the Java multi-threading interview questions asked quite often.

Even if we leave the interviews aside it is important to know the concept of why anything is done that way. So let's see the reasons behind putting the wait(), notify() and notifyAll() methods in Object class though these methods are used in multi-threading scenarios.

wait(), notify() and notifyAll() methods are defined as follows in Java Object class-

public final native void wait(long timeout) throws InterruptedException;

public final native void notify();

public final native void notifyAll();

There are 2 more overloaded wait methods

public final void wait() throws InterruptedException;

public final void wait(long timeout, int nanos) throws InterruptedException;

Reasons for putting these methods in Object class

  1. First of all we have to know what wait() and notify() do in order to be clear why these methods are in Object class.
    • wait- wait method tells the current thread to give up monitor and go to sleep.
    • notify- Wakes up a single thread that is waiting on this object's monitor.

    So you see wait() and notify() methods work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait() method and through notify() method (or notifyAll) threads which are waiting on the object's monitor are notified that threads can wake up.

    Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class.
    To reiterate threads wait on an Object's monitor (lock) and notify() is also called on an object to wake up a thread waiting on the Object's monitor.

  2. wait(), notify() and notifyAll() are used for inter-thread communication. But threads themselves have no knowledge of each others status. It is the shared object among the threads that acts as a communicator among the threads.

    Threads lock an object, wait on an object and notify an object. When a wait method is called it checks which thread has the lock on the object and that is the thread which has to give up the lock. Same way notify() method when called looks for all the thread that are waiting to get hold of the Object's monitor and wakes one of the thread, notifyAll() wakes up all the thread that are waiting on an Object's monitor.

    So it is the shared object among the thread which allows them to communicate with each other and wait(), notify() and notifyAll() are the methods used for inter-thread communication.

That's all for this topic Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  2. Can we Start The Same Thread Twice in Java
  3. Difference Between sleep and wait in Java Multi-Threading
  4. isAlive() And join() Methods in Java Multi-Threading
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like-

  1. Varargs (Variable-length Arguments) in Java
  2. static Import in Java With Examples
  3. Difference Between Abstract Class And Interface in Java
  4. Java Object Cloning - clone() Method
  5. How to Convert ArrayList to Array in Java
  6. Callable and Future in Java With Examples
  7. Java ArrayBlockingQueue With Examples
  8. ConcurrentHashMap in Java With Examples

Sunday, January 3, 2021

Spring Component Scan to Automatically Discover Beans

In the post how to autowire using XML config and how to autowire using annotation you have already seen how Spring can automate the injection of dependencies. That helps in cutting down the configuration you have to do by eliminating the use of <property> and <constructor-arg> tags for wiring the bean references. But Spring can even automatically discover beans using <context:component-scan> element. In this post we'll see how to configure and use component scanning in Spring.


Automatic discovery of beans in Spring

Spring goes even further than autowiring and it can automatically discover beans for you. That can be done using <context:component-scan> element or @ComponentScan annotation, it configures Spring to automatically discover beans and declare them for you. This removes the need to use XML to perform bean registration and for most of the classes you don’t need <bean> element to declare and wire beans.

Note here that - The use of <context:component-scan> implicitly enables the functionality of <context:annotation-config>. There is usually no need to include the <context:annotation-config> element when using <context:component-scan>. So <context:component-scan> will do everything which <context:annotation-config> does and it provides the added functionality of auto-discovery of beans. In fact difference between <context:annotation-config> and <context:component-scan> is one of the frequently asked interview question.

Spring component scan configuration requirement

If you are using XML configuration then you need to use context:component-scan with base-package. The base-package attribute tells <context:component-scan> from which package it needs to start its component scan.

<?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: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/context
http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="org.example"/>
</beans>

If you are using Spring Java configuration then you need to add @ComponentScan annotation along with @Configuration annotation-

@Configuration
@ComponentScan(basePackages="org.example")
public class AppConfig {
    
}

You can annotate a Java class with @ComponentScan and provide the package which is to be scanned with basePackage attribute. You don't need to provide any code with in the class.

Annotations used in Spring for auto-discovery

Using componentscan element is half of the picture, you need to annotate your classes which needs to be auto-discovered with one of these annotations @Component, @Service, @Controller, @Repository

  • @Component- It is a generic stereotype for any Spring-managed component.
  • @Service- More suitable for a class used as a service.
  • @Repository- This annotation is a marker for any class that fulfills the role or stereotype of a repository (also known as Data Access Object or DAO).
  • @Controller- More suitable for a class used in presentation layer as a controller.
  • Any custom annotation that is itself annotated with @Component.

According to the Spring reference doc-

"you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework."

Spring component scanning example

Here we have a class PayServiceImpl which has a field payment of type IPayment which we have to autowire. Also PayServiceImpl and CashPayment (implementing class of interface IPayment) should be auto discovered. Since Spring promotes loose coupling so it is always recommended to code to interfaces. So we'll also create interfaces for the classes.

IPayService Interface

public interface IPayService {
 void performPayment();
}

PayServiceImpl class

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

@Service
public class PayServiceImpl implements IPayService {
 @Autowired
 private IPayment payment;

 public void performPayment() {
  // calling method on Ipayment implementing class
  payment.executePayment();
 }
 
 public IPayment getPayment() {
  return payment;
 }
 
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }
}

Here note that the class is annotated with @Service annotation, that's how it is made sure that this class is discovered while a component scan is done. Also note that the dependency to the payment is annotated with the annotation @Autowired. That's how Spring will automatically detect this dependency and inject it.

Interface IPayment

public interface IPayment {
 void executePayment();
}

Class CashPayment

import org.springframework.stereotype.Component;

@Component
public class CashPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Cash Payment - "); 
 }
}

Spring component scan XML 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"
    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-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
   <context:component-scan base-package="org.netjs.prog" />  
 
</beans>

If you are using XML configuration then you need to use context:component-scan with base-package. I have created Java classes in the package org.netjs.prog so that's what I'll give as the base package. Please change accordingly.

You can run it using the following program-

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
  public static void main( String[] args ){  
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
     ("appcontext.xml");
    IPayService bean = (IPayService) context.getBean("payServiceImpl");
    bean.performPayment();
    context.close();
  }
}

Here note that by default Spring will use the class name as the bean id (camel cased) while registering it in Spring. That's why you can find the bean using this- context.getBean("payServiceImpl");

If you want to give your own name let's say payService then it can be done like this-

@Service("payService")
public class PayServiceImpl implements IPayService

Then in order to get the bean you have to use this name -

IPayService bean = (IPayService) context.getBean("payService");

Spring component scan example with Java config

If you are using Java class then you just need this

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

@Configuration
@ComponentScan(basePackages="org.netjs.prog")
public class AppConfig {
 
}

In that case you can run it using the following program-

import org.netjs.config.AppConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class App {
  public static void main( String[] args ){
    AbstractApplicationContext context = new AnnotationConfigApplicationContext
     (AppConfig.class);
    IPayService bean = (IPayService) context.getBean("payServiceImpl");
    bean.performPayment();
    context.close();
  }
}

Here note that AnnotationConfigApplicationContext is used to create the Spring application context which takes the JavaConfig class as input.

That's all for this topic Spring Component Scan to Automatically Discover Beans. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Constructor Based Dependency Injection
  2. Spring Java Configuration Example Using @Configuration
  3. Autowiring in Spring Using @Autowired and @Inject Annotations
  4. Autowiring in Spring Using XML Configuration
  5. @Conditional Annotation in Spring

You may also like-

  1. How to Read Properties File in Spring Framework
  2. @Resource Annotation in Spring Autowiring
  3. Circular Dependency in Spring Framework
  4. Java LinkedBlockingQueue With Examples
  5. Java ThreadLocal Class With Examples
  6. Abstraction in Java
  7. How HashMap Works Internally in Java
  8. Print Odd-Even Numbers Using Threads And wait-notify Java Program

Saturday, January 2, 2021

Autowiring in Spring Using @Autowired and @Inject Annotations

Though autowiring of the beans can be done using XML configuration for autowiring but Spring goes one step further and provides autowiring using annotations which leads to shorter and more concise configuration.

Broadly Spring provides two ways to annotate beans for autowiring-

  • Using @Autowired annotation- It is a spring specific annotation.
  • Using @Inject annotation- It is provided by JSR-330 (Dependency Injection for Java) annotations contained in the javax.inject package. Spring supports this annotation.

In this post we'll see Spring autowiring examples using both @Autowired and @Inject annotations.


Configuration required for autowiring using annotation

To enable autowiring using annotation in Spring, you have to register 'AutowiredAnnotationBeanPostProcessor' class.

  • You can directly provide this class in xml config-
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    
  • You can include the <context:annotation-config/> tag in an XML-based Spring configuration (notice the inclusion of the context namespace in XML). This is the preferred way.
    <?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: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/context
    http://www.springframework.org/schema/context/spring-context.xsd">
      <context:annotation-config/>
    </beans>
    

    By using <context:annotation-config/> tag following post-processors are implicitly registered AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor and RequiredAnnotationBeanPostProcessor.

  • You can include the <context:component-scan/> tag.

Refer Using component-scan in Spring to Automatically Discover Bean to see why <context:component-scan/> should be used instead of <context:annotation-config/>

Autowiring in Spring using @Autowired annotation

Note that @Autowired annotation can be applied on-

  • setter method
  • constructor
  • field
Here we'll see example for all of these options.

Spring @Autowired annotation on setter

When @Autowired annotation is used on a setter, it is equivalent to autowiring="byType" in autowiring using configuration file.

Here we have a class PayServiceImpl which has a field payment of type IPayment which we have to autowire. Also class CashPayment which implements IPayment interface.

interface IPayService

public interface IPayService {
 void performPayment();
}

PayServiceImpl class

import org.springframework.beans.factory.annotation.Autowired;
public class PayServiceImpl implements IPayService {
  private IPayment payment;

  public void performPayment() {
    // calling method on Ipayment implementing class
    payment.executePayment();
  }

  public IPayment getPayment() {
    return payment;
  }

  @Autowired
  public void setPayment(IPayment payment) {
    this.payment = payment;
  }
}

Here note the @Autowired annotation on setPayment() method.

Interface IPayment

public interface IPayment {
 void executePayment();
}

CashPayment class

public class CashPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Cash Payment - "); 
 }
}

XML configuration file

<?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-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:annotation-config/>  
 
 <bean id="cashPaymentBean" class="org.netjs.prog.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.PayServiceImpl">
      <!-- <property name="payment" ref="cashPaymentBean" /> -->
  </bean> 
</beans>

Here note the inclusion of <context:annotation-config/> tag which is required for autowired annotation. Also note that ref for cashPaymentBean is no longer required as a property in paymentBean (it is commented in the config). It will be injected automatically now because of the @Autowired annotation.

You can use the following code to run this program -

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
  public static void main( String[] args ){  
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
       ("appcontext.xml");
    // Getting PayServiceImpl 
    IPayService bean = (IPayService) context.getBean("paymentBean");
    bean.performPayment();
    context.close();
  }
}

Output

Perform Cash Payment-

@Autowired annotation on field

When @Autowired annotation is used on a property, it is equivalent to autowiring="byType" when autowiring is done using configuration file.

In this case PayServiceImpl will change to have @Autowired annotation on the field. When using @Autowired with field you don't even need the setter method for that field.

PayServiceImpl class

public class PayServiceImpl implements IPayService {
 @Autowired
 private IPayment payment;

 public void performPayment() {
  // calling method on Ipayment implementing class
  payment.executePayment();
 }
 
 public IPayment getPayment() {
  return payment;
 }
 
 /*public void setPayment(IPayment payment) {
  this.payment = payment;
 }*/
}

Rest of the things remain the same as used in the example for @Autowired on setter.

@Autowired annotation on constructor

When @Autowired annotation is used on a bean's constructor, it is equivalent to autowiring="constructor" when autowiring is done using configuration file.

In this case PayServiceImpl will change to have @Autowired annotation on the constructor of the class. When using @Autowired on constructor you don't even need the setter method for that field.

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

public class PayServiceImpl implements IPayService {
 
 private IPayment payment;
 // Constructor 
 @Autowired
 PayServiceImpl(IPayment payment){
  this.payment = payment;
 }

 public void performPayment() {
  // calling method on Ipayment implementing class
  payment.executePayment();
 }
 
 public IPayment getPayment() {
  return payment;
 }
 
 /*public void setPayment(IPayment payment) {
  this.payment = payment;
 }*/
}

Rest of the things remain the same as used in the example for @Autowired on setter.

@Autowired annotation on arbitrary methods

You can also apply the annotation to methods with arbitrary names and/or multiple arguments, Example as taken from Spring reference doc

public class MovieRecommender {
  private MovieCatalog movieCatalog;
  private CustomerPreferenceDao customerPreferenceDao;
  @Autowired
 public void prepare(MovieCatalog movieCatalog, CustomerPreferenceDao customerPreferenceDao) {
   this.movieCatalog = movieCatalog;
   this.customerPreferenceDao = customerPreferenceDao;
 }
 // ...
}

@Autowired annotation with required=false

The default behavior for the annotation is to treat annotated methods, constructors, and fields as indicating required dependencies. Thus the autowiring fails whenever zero candidate beans are available. You can make the autowiring optional to avoid such errors, this can be done by using required="false" with the @Autowired annotation.

@Autowired(required=false)
private IPayment payment;

Conflict resolution using Spring @Qualifier annotation

What if there are more than one bean in the configuration file whose type is compatible with the autowired property. In that case Spring won't be able to decide which bean to use, it will throw an exception instead.

In the above application we had used only one implementation of IPayment, CashPayment so there was no problem in automatically wiring it. Now suppose we have one more implementation of the IPayment interface, Credit Payment. In that case with the current setup you'll get NoUniqueBeanDefinitionException because Spring won't know which Payment class to wire.

CreditPayment class

public class CreditPayment implements IPayment {
 public void executePayment() {
  System.out.println("Performing credit payment ");
 }
}

Adding CreditPayment definition in config

<bean id="creditPaymentBean" class="org.netjs.prog.CreditPayment" />

Now if you run the code you will get NoUniqueBeanDefinitionException-

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'paymentBean': 
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private org.netjs.prog.IPayment org.netjs.prog.PayServiceImpl.payment; 
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type [org.netjs.prog.IPayment] is defined: expected single matching bean but found 2: 
cashPaymentBean,creditPaymentBean
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)

In this kind of scenario, to avoid ambiguity you can use @Qualifier annotation to qualify the bean. Suppose you want to inject cashPaymentBean then you can qualify it by passing bean name with the qualifier annotation.

@Qualifier example to avoid NoUniqueBeanDefinitionException error

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class PayServiceImpl implements IPayService {
 @Autowired
 @Qualifier("cashPaymentBean")
 private IPayment payment;

 public void performPayment() {
  // calling method on Ipayment implementing class
  payment.executePayment();
 }
 
 public IPayment getPayment() {
  return payment;
 }
 
 /*public void setPayment(IPayment payment) {
  this.payment = payment;
 }*/
}

Using JSR-330 @Inject annotation

Instead of @Autowired, @javax.inject.Inject annotation can be used for autowiring in Spring. @Inject annotation is part of the standard JSR-330: Dependency injection for Java. So, if you don't want Spring specific annotations and want to go with standard annotation then use @Inject.

As with @Autowired, it is possible to use @Inject at the class-level, field-level, method-level and constructor-argument level.

Note one thing though. @Inject has no 'required' attribute as provided with @Autowired, so @Inject annotated dependencies can't be optional, an exception will be thrown if they are not fulfilled.

@Named annotation

If you would like to use a qualified name for the dependency that should be injected, instead of @Qualifier you can use @Named annotation which is again part of the standard JSR-330: Dependency injection for Java.

Spring autowiring example with @Inject and @Named annotations

Let's take the same case where we have two payment classes CashPayment and CreditPayment. If you want to make sure that CashPayment bean is the one which is injected then using @Inject and @Named annotations the PayServiceImpl class will look like -

import javax.inject.Inject;
import javax.inject.Named;

public class PayServiceImpl implements IPayService {
 @Inject
 @Named("cashPaymentBean")
 private IPayment payment;

 public void performPayment() {
  // calling method on Ipayment implementing class
  payment.executePayment();
 }
 
 public IPayment getPayment() {
  return payment;
 }
 
 @Inject
 public void setPayment(@Named("cashPaymentBean")IPayment payment) {
  this.payment = payment;
 }
}

Note here that @Inject annotation is used with the setter.

Configuration file for the example

<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-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:annotation-config/>  
 
 <bean id="cashPaymentBean" class="org.netjs.prog.CashPayment" />
 
 <bean id="creditPaymentBean" class="org.netjs.prog.CreditPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.PayServiceImpl">
  </bean>
</beans>

Are annotations better than XML for configuring Spring?

According to the Spring reference doc-

The introduction of annotation-based configurations raised the question of whether this approach is 'better' than XML. The short answer is it depends. The long answer is that each approach has its pros and cons, and usually it is up to the developer to decide which strategy suits them better. Due to the way they are defined, annotations provide a lot of context in their declaration, leading to shorter and more concise configuration. However, XML excels at wiring up components without touching their source code or recompiling them. Some developers prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and, furthermore, that the configuration becomes decentralized and harder to control.

That's all for this topic Autowiring in Spring Using @Autowired and @Inject Annotations. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Autowiring in Spring Using XML Configuration
  2. Dependency Injection in Spring Framework
  3. How to Read Properties File in Spring Framework
  4. Difference Between component-scan And annotation-config in Spring
  5. @Resource Annotation in Spring Autowiring

You may also like-

  1. Bean Definition Inheritance in Spring
  2. Spring p-namespace For Shorter XML Configuration
  3. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  4. Difference Between throw And throws in Java
  5. How to Sort an ArrayList in Descending Order in Java
  6. LinkedHashMap in Java With Examples
  7. How to Create PDF From XML Using Apache FOP
  8. How to Find Last Modified Date of a File in Java