Spring MVC 4 Autowire Example

Spring MVC 4 Autowire Example shows a real time implementation of autowiring a bean to required service.

Spring @Autowired annotation is used for autowiring a bean to constructor, setter method, property or methods.

Following are the different ways we can do autowire feature

  1. Auto-Wiring "no" -> This is default mode means no autowiring
  2. Auto-Wiring "byName" -> This means autowiring happens using the matching property name
  3. Auto-Wiring "byType" -> This means autowiring happens using the matching type
  4. Auto-Wiring "constructor" -> This means autowiring happens through constructor according to the exact arguments
Note

I am going to re-use Spring MVC 4 REST Example

I have made following changes on Spring MVC 4 REST Example to enabling autowire feature (You can see the changed code below)

1) Created a new class "StudentService" with annotation @Service("StudentService"), for acting as a service (see below code)
2) Modified class "StudentController" with annotation @Autowired in above created class(ie; StudentService) (see below code)
3) Created a spring-service.xml and defined a <bean id="studentService" class="com.student.dao.StudentService" /> bean (see below code)
4) Added contextConfigLocation in web.xml for loading spring-service.xml (see below code)
5) Added <context:component-scan base-package="com.student.dao" /> in rest-servlet.xml (see below code)

You can see the project structure below

Spring MVC 4 Autowire Example

StudentService.java

package com.student.dao;

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

import org.springframework.stereotype.Service;

import com.student.domain.Student;

@Service("StudentService")
public class StudentService {

   
public List<Student> getAllStudents() {
       
List<Student> Students = new ArrayList<Student>();

        Student student =
new Student();
        student.setName
("Rockey");
        Students.add
(student);

        student =
new Student();
        student.setName
("Jose");
        Students.add
(student);

       
return Students;
   
}

   
public Student getStudentById(int StudentId) {
       
Student student = null;
       
if (StudentId == 1) {
           
student = new Student();
            student.setName
("Jose");
       
}else{
           
student = new Student();
            student.setName
("Invalid Student");
       
}
       
return student;
   
}
}

StudentController.java

In StudentController class, we have added @RestController annotation which removing the need to add @ResponseBody to each of your @RequestMapping methods.

@RequestMapping annotation is used for mapping web requests to corresponding handler classes and handler methods

@Autowired annotation is used for autowiring "StudentService" on StudentController

package com.student.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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.student.dao.StudentService;
import com.student.domain.Student;

@RestController
@RequestMapping
("/service/student/")
public class StudentController {
   
@Autowired
   
private StudentService studentService;

   
   
@RequestMapping(method = RequestMethod.GET, headers = "Accept=application/json")
   
public List<Student> getAllStudents() {
       
List<Student> Students = studentService.getAllStudents();
       
return Students;
   
}
   
   
@RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
   
public Student getStudentById(@PathVariable int id) {
       
Student Student = studentService.getStudentById(id);
       
return Student;
   
}
}

rest-servlet.xml

The name for rest-servlet.xml is must match the servlet-name we have provided on web.xml. In our case we have provided servlet-name as rest, so we need to append "-servlet.xml"

Below code is used for Spring auto detection feature of finding the packages where the controller is defined

<context:component-scan base-package="com.student.controller" />
<context:component-scan base-package="com.student.dao" />

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	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-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<context:component-scan base-package="com.student.controller" />
	<context:component-scan base-package="com.student.dao" />
	<mvc:annotation-driven />
</beans>

spring-service.xml

We are defining a new bean "studentService" inside spring-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	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-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<bean id="studentService" class="com.student.dao.StudentService" />

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
        classpath:spring-service.xml
    </param-value>
	</context-param>

	<display-name>Spring MVC Rest</display-name>
	<servlet>
		<servlet-name>rest</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>rest</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

</web-app>
Run

Spring MVC 4 Autowire Example

Spring MVC 4 Autowire Example









1 Responses to "Spring MVC 4 Autowire Example"
  1. David 2016-08-31 00:25:41.0

Your email address will not be published. Required fields are marked *