Hello world Spring RestController

To get started create an Maven project with the Spring initializer inside Intellij or on the Spring website.

org.springframework.boot
spring-boot-starter-web

This should give you this dependency in your pom.xml.

We create a class where we make a controller that returns Hello World in JSON format.

@RestController
@RequestMapping("/hello")
public class BasicRestController {

    @GetMapping("rest")
    public List getHello() {
        List stringList = new ArrayList<>(Arrays.asList("Hello", "World"));
        return stringList;
    }
}
  • @RestController: is a specialized Component for returning JSON objects
  • @RequestMapping: is the first part of the URL you go to
  • @GetMapping: is the second part of the URL you go to

Your main class should look like this:

@SpringBootApplication
public class BasicApplication{

	public static void main(String[] args) {
		SpringApplication.run(BasicApplication.class, args);
	}
}

@SpringBootApplication is short for

  • @Configuration: There are beans inside this class
  • @EnableAutoConfiguration: Add all possible beans
  • @ComponentScan: Look for Components and Component extensions (@Controller / @RestController, et cetera)
  • Because we got an dependency on spring-webmvc Spring Boot autoconfigures @EnableWebMvc. This makes it a web application.

When you run the application and go to http://localhost:8080/hello/rest you get the following JSON response:

["Hello","World"]

This is the very basics of Spring RestControllers.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s