Spring REST 4: @RestController

@Restcontroller

  • Extension of @Controller
  • Handles REST requests and response

Development Process

Maven dependency for Spring MVC and Jackson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- Add Jackson for JSON converters-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>

<!-- Add Spring MVC and REST support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>

<!-- Add Servlet support for Spring's AbstracAnnotationConfigDispatcherServletInitializer -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>

All Java Config: @Configuration

1
2
3
4
5
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.xliu")
public class DemoAppConfig {
}

All Java Config: Servlet Initializer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}

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

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

Create Spring REST Service using @RestController

1
2
3
4
5
6
7
8
@RestController
@RequestMapping("/test")
public class DemoRestController {
@GetMapping("/hello")
public String sayHello(){
return "Hello!";
}
}

Address: http://localhost:8080/test/hello