Spring Framework Basics: What Is Inversion of Control?

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

What You Will Learn

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

What Is Inversion of Control?

Approach-1

Have a look at the following implementation of ComplexAlgorithmImpl:

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

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

Approach-2

Now, look at this implementation for a change:

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

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

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

Comparing Approach-1 and Approach-2

Approach-1

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

Approach-2

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

Inversion Of Control At Play!

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

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

This is Inversion of Control.

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

Why Is Inversion of Control Important?

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

Advantages of Inversion Of Control

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

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

image info

Summary

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

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

50+ Java Interview Questions for Programmers

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

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

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

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

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

Java Interview Questions and Answers

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Additional Resources

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

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

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

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

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

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

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

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

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

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

Request: http://localhost:8080/users 

Accept: application/json 

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

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

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

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

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

Image title

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

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

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

Conclusion

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

@RestController vs @Controller : Spring Framework

Spring MVC Framework and REST

Spring’s annotation-based MVC framework simplifies the process of creating RESTful web services. The key difference between a traditional Spring MVC controller and the RESTful web service controller 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.  For a detailed description of creating RESTful web services using the Spring framework, click here.

Image title

Figure 1: Spring MVC traditional workflow

Spring MVC REST Workflow

The following steps describe a typical Spring MVC REST workflow:

  1. The client sends a request to a web service in URI form.
  2. The request is intercepted by the DispatcherServlet which looks for Handler Mappings and its type.
    • The Handler Mappings section defined in the application context file tells DispatcherServlet which strategy to use to find controllers based on the incoming request.
    • Spring MVC supports three different types of mapping request URIs to controllers: annotation, name conventions, and explicit mappings.
  3. Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.

In Figure 1, notice that in the traditional workflow the ModelAndView object is forwarded from the controller to the client. Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. Beginning with Version 4.0, this process is simplified even further with the introduction of the @RestController annotation. Each approach is explained below.

Using the @ResponseBody Annotation

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.

3.x-diagram

Figure 2: Spring 3.x MVC RESTful web services workflow

Behind the Scenes

Spring has a list of HttpMessageConverters registered in the background. The responsibility of the HTTPMessageConverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.

Code Example

Let’s walk through @ResponseBody with a simple example.

Project Creation and Setup

  1. Create a Dynamic Web Project with Maven support in your Eclipse or MyEclipse IDE.
  2. Configure Spring support for the project.• If you are using Eclipse IDE, you need to download all Spring dependencies and configure your pom.xml to contain those dependencies.• In MyEclipse, you only need to install the Spring facet and the rest of the configuration happens automatically.
  3. Create the following Java class named Employee. This class is our POJO.
package com.example.spring.model;
import javax.xml.bind.annotation.XmlRootElement;
 @XmlRootElement(name = “Employee”)
 public class Employee {
     String name
      String email;
    public String getName() {
       return name;
    }
    public void setName(String name) {
       this.name = name;
    }
     public String getEmail() {
                 return email;
     }
     public void setEmail(String email) {
       this.email = email;
     }
     public Employee() {
     }
 }

Then, create the following @Controller class:

 package com.example.spring.rest;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.spring.model.Employee;
@Controller
@RequestMapping("employees")
public class EmployeeController {
     Employee employee = new Employee();
     @RequestMapping(value = “/{name}”, method = RequestMethod.GET, produces = “application/json”)
     public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) {
        employee.setName(name);
        employee.setEmail(“employee1@genuitec.com”);
     return employee;
    }
    @RequestMapping(value = “/{name}.xml”, method = RequestMethod.GET, produces = “application/xml”)
     public @ResponseBody Employee getEmployeeInXML(@PathVariable String name) {
        employee.setName(name);
        employee.setEmail(“employee1@genuitec.com”);
        return employee;
     }
 }
 Notice the @ResponseBody added to each of the @RequestMapping methods in the return value. After that, it’s a two-step process:
  1. Add the <context:component-scan> and <mvc:annotation-driven /> tags to the Spring configuration file.
    • <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
    • <mvc:annotation-driven/> adds support for reading and writing JSON/XML if the Jackson/JAXB libraries are on the classpath.
    • For JSON format, include the jackson-databind jar and for XML include the jaxb-api-osgi jar to the project classpath.
  2. Deploy and run the application on any server (e.g., Tomcat). If you are using MyEclipse, you can run the project on the embedded Tomcat server.JSON—Use the URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob and the following output displays:output_json-cropXML — Use the
    URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob.xml and the following output displays:output_xml

Using the @RestController Annotation

Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default. Click here to learn more.
4.x-diagram

To use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. The resultant class should look like the following:

 package com.example.spring.rest;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RestController;
 import com.example.spring.model.Employee;
@RestController
 @RequestMapping(“employees”)
 public class EmployeeController {
     Employee employee = new Employee();
     @RequestMapping(value = “/{name}”, method = RequestMethod.GET, produces = “application/json”)
     public Employee getEmployeeInJSON(@PathVariable String name) {
        employee.setName(name);
        employee.setEmail(“employee1@genuitec.com”);
        return employee;
    }
     @RequestMapping(value = “/{name}.xml”, method = RequestMethod.GET, produces = “application/xml”)
     public Employee getEmployeeInXML(@PathVariable String name) {
        employee.setName(name);
        employee.setEmail(“employee1@genuitec.com”);
     return employee;
     }
 }

Note that we no longer need to add the @ResponseBody to the request mapping methods. After making the changes, running the application on the server again results in same output as before.

Conclusion

As you can see, using @RestController is quite simple and is the preferred method for creating MVC RESTful web services starting from Spring v4.0. I would like to extend a big thank you to my co-author, Swapna Sagi, for all of her help in bringing you this information!

@RestController vs. @Controller : Spring Framework

Spring MVC Framework and REST

Spring’s annotation-based MVC framework simplifies the process of creating RESTful web services. The key difference between a traditional Spring MVC controller and the RESTful web service controller 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.  For a detailed description of creating RESTful web services using the Spring framework, click here.

Image title

Figure 1: Spring MVC traditional workflow

Spring MVC REST Workflow

The following steps describe a typical Spring MVC REST workflow:

  1. The client sends a request to a web service in URI form.
  2. The request is intercepted by the DispatcherServlet which looks for Handler Mappings and its type.
    • The Handler Mappings section defined in the application context file tells DispatcherServlet which strategy to use to find controllers based on the incoming request.
    • Spring MVC supports three different types of mapping request URIs to controllers: annotation, name conventions, and explicit mappings.
  3. Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.

In Figure 1, notice that in the traditional workflow the ModelAndView object is forwarded from the controller to the client. Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. Beginning with Version 4.0, this process is simplified even further with the introduction of the @RestController annotation. Each approach is explained below.

Using the @ResponseBody Annotation

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.

3.x-diagram

Figure 2: Spring 3.x MVC RESTful web services workflow

Behind the Scenes

Spring has a list of HttpMessageConverters registered in the background. The responsibility of the HTTPMessageConverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.

Code Example

Let’s walk through @ResponseBody with a simple example.

Project Creation and Setup

  1. Create a Dynamic Web Project with Maven support in your Eclipse or MyEclipse IDE.
  2. Configure Spring support for the project.• If you are using Eclipse IDE, you need to download all Spring dependencies and configure your pom.xml to contain those dependencies.• In MyEclipse, you only need to install the Spring facet and the rest of the configuration happens automatically.
  3. Create the following Java class named Employee. This class is our POJO.
package com.example.spring.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Employee")
public class Employee {
 String name; 
 String email;
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getEmail() {
 return email;
 }
 public void setEmail(String email) {
 this.email = email;
 }
 public Employee() {
 } 
}
 Then, create the following @Controller class:
package com.example.spring.rest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.spring.model.Employee;
@Controller
@RequestMapping("employees")
public class EmployeeController {
 Employee employee = new Employee();
 @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
 public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) {
 employee.setName(name);
 employee.setEmail("employee1@genuitec.com");
 return employee; 
 }
 @RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml")
 public @ResponseBody Employee getEmployeeInXML(@PathVariable String name) {
 employee.setName(name);
 employee.setEmail("employee1@genuitec.com");
 return employee; 
 }
}
 Notice the @ResponseBody added to each of the @RequestMapping methods in the return value. After that, it’s a two-step process:
  1. Add the <context:component-scan> and <mvc:annotation-driven /> tags to the Spring configuration file.
    • <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
    • <mvc:annotation-driven/> adds support for reading and writing JSON/XML if the Jackson/JAXB libraries are on the classpath.
    • For JSON format, include the jackson-databind jar and for XML include the jaxb-api-osgi jar to the project classpath.
  2. Deploy and run the application on any server (e.g., Tomcat). If you are using MyEclipse, you can run the project on the embedded Tomcat server.JSON—Use the URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob and the following output displays:output_json-crop

    XML — Use the
    URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob.xml and the following output displays:output_xml

Using the @RestController Annotation

Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default. Click here to learn more.
4.x-diagram

To use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. The resultant class should look like the following:

package com.example.spring.rest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.spring.model.Employee;
@RestController
@RequestMapping("employees")
public class EmployeeController {
 Employee employee = new Employee();
 @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
 public Employee getEmployeeInJSON(@PathVariable String name) {
 employee.setName(name);
 employee.setEmail("employee1@genuitec.com");
 return employee;
 }
 @RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml")
 public Employee getEmployeeInXML(@PathVariable String name) {
 employee.setName(name);
 employee.setEmail("employee1@genuitec.com");
 return employee; 
 } 
}

Note that we no longer need to add the @ResponseBody to the request mapping methods. After making the changes, running the application on the server again results in same output as before.

Conclusion

As you can see, using @RestController is quite simple and is the preferred method for creating MVC RESTful web services starting from Spring v4.0. I would like to extend a big thank you to my co-author, Swapna Sagi, for all of her help in bringing you this information!

Difference between Setter vs Constructor Injection in Spring

Spring Setter vs Constructor Injection

Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is a dependency or via a constructor argument. The first way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article. The difference between Setter Injection and Constructor Injection in Spring is also a popular Spring framework interview question.Some time interviewer also asks as When do you use Setter Injection over Constructor injection in Spring or simply benefits of using setter vs constructor injection in Spring framework. Points discussed in this article not only help you to understand Setter vs Constructor Injection but also Spring’s dependency Injection process.

By the way, if you are new in Spring framework and learning it, you may want to take a look at my list of 5 good books to learn Spring framework. That will certainly help in  your learning process. Since Spring is now a must have skill for Java programmers, it worth putting time and effort to learn this powerful framework

Difference between Setter and Constructor Injection in Spring framework

As I said earlier Spring supports both setter and constructor Injection which are two standard way of injecting dependency on beans managed by IOC constructor. Spring framework doesn’t support Interface Injection on which dependency is injected by implementing a particular interface. In this section we will see a couple of difference between setter and constructor Injection, which will help you decide when to use setter Injection over constructor Injection in Spring and vice-versa.

1) The fundamental difference between setter and constructor injection, as their name implies is How dependency is injected.  Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring’s IOC container. On the other hand constructor injection uses constructor to inject dependency on any Spring-managed bean.
2) Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml . Since setter method has name e.g. setReporotService() by reading Spring XML config file you know which dependency you are setting. While in constructor injection, since it uses an index to inject the dependency, it’s not as readable as setter injection and you need to refer either Java documentation or code to find which index corresponds to which property.
3) Another difference between setter vs constructor injection in Spring and one of the drawback of  setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.
4) One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call the constructor, a new object is gets created.

5) One of our reader Murali Mohan Reddy pointed out one more difference between Setter and Constructor injection in Spring, where later can help if there is a circular dependency between two object A and B.
If Object A and B are dependent each other i.e A is depends ob B and vice-versa. Spring throws ObjectCurrentlyInCreationException while creating objects of A and B bcz A object cannot be created until B is created and vice-versa. So spring can resolve circular dependencies through setter-injection. Objects constructed before setter methods invoked.
See comment section for more inputs from other readers.

When to use Setter Injection over Constructor Injection in Spring

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is much bigger concern. Also drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using “dependency-check” attribute of  tag or tag. Another worth noting point to remember while comparing Setter Injection vs Constructor Injection is that, once number of dependency crossed a threshold e.g. 5 or 6 its handy manageable to passing dependency via constructor. Setter Injection is preferred choice when number of dependency to be injected is lot more than normal, if some of those arguments is optional than using Builder design pattern is also a good option.
In Summary, both Setter Injection and Constructor Injection has there own advantage and disadvantage. The good thing about Spring is that it doesn’t restrict you to use either Setter Injection or Constructor Injection and you are free to use both of them in one Spring configuration file. Use Setter injection when a number of dependencies are more or you need readability. Use Constructor Injection when Object must be created with all of its dependency.

 

Spring Security Example Tutorial – How to limit number of User Session in Java

Spring security can limit number of session a user can have. If you are developing web application specially secure web application in Java J2EE then you must have come up with requirement similar to online banking portals have e.g. only one session per user at a time or no concurrent session per user. You can also implement this functionality without using spring security but with Spring security its just piece of cake with coffee :). Spring Security provides lots of Out of Box functionality a secure enterprise or web application needed like authentication, authorization, session management, password encoding, secure access, session timeout etc. In our spring security example we have seen how to do LDAP Authentication in Active directory using spring security and in this spring security example we will see how to limit number of session user can have in Java web application or restricting concurrent user session.

Spring Security Example: Limit Number of User Session

As I said it’s simple and easy when you use spring security framework or library. In fact is all declarative and no code is require to enable concurrent session disable functionality. You will need to include following xml snippet in your Spring Security Configuration file mostly named as applicaContext-security.xml. Here is sample spring security Example of limiting user session in Java web application:

<session-management invalid-session-url="/logout.html">
    <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>

As you see you can specify how many concurrent session per user is allowed, most secure system like online banking portals allow just one authenticate session per user. You can even specify a URL where user will be taken if they submit an invalid session identifier can be used to detect session timeout. Session-management element is used to capture session related stuff. Max-session specify how many concurrent authenticated session is allowed and if error-if-maximum-exceeded set to true it will flag error if user tries to login into another session.

Dependency

This code has dependency on spring-security framework. You need to download spring security jar like spring-security-web-3.1.0.jar and add into application classpath.

This simple example of spring security shows power of spring security, a small piece of xml snippet can add very useful and handy security feature in your Java web application. I recommend using spring security for your new or existing Java web application created using Servlet JSP.

That’s all on how to limit number of user session using spring security in Java web application. Let me know if you face any issue while implementing this security feature in your project.