Saturday, September 1, 2018

How to use Spring boot with VScode

Prerequisites

  • VScode
  • Java 1.8 (or 11 or 15)

Configure a project

You can use start.spring.io to configure it. I configured it like the following:

Please note that I added "Web" and "Thymeleaf". To add these dependencies, search for dependency in the "Search for dependencies" and click the suggestion. After configuring everything, click on "Generate Project".

VScode

Once you click on "Generate Project", you will get a zip file. Extract "demo" folder of the zip. 

Drag and drop the extracted "demo" on VScode. 


Open pom.xml by double-clicking on the "pom.xml".

Press F5 then click on "Java". The project will be compiled. 

Hello World

Controller

Create "controller" folder in "demo" folder. Then create "HelloController.java" in "controller" folder. 

Write as follows in the HelloController.java. Then save it by "ctrl + s".
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController{
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String get(){
        return "hello";
    }
}

Template

Create a "hello.html" in "templates" folder as follows: 

Write as follows in "hello.html" then save it.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
Hello World!
</body>
</html>

Check from browser

Now stop the debug mode (if it is still running).

Then press F5. Debug mode is restarted after compiling the project. Open http://localhost:8080 . If eveything is done correctly, you will see "Hello World!".


Auto import of libraries in VScode

Auto import is an important functionality of IDE and this can be done in VScode too.
Press "ctrl + ." to get suggestion of automatic import of Java library in VScode:
Pressing ctrl + . on the "FetchType"


launch.json, setting.json, task.json

It is useful, in .vscode, if you write launch.json as follows:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "java",
            "name": "Debug (Launch)-DemoApplication<demo>",
            "request": "launch",
            "mainClass": "com.example.demo.DemoApplication",
            "projectName": "demo"
        }
    ]
}

Also setting.json:

{
    "java.configuration.updateBuildConfiguration": "automatic",
}

task.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "compile",
            "type": "shell",
            "command": "mvn clean spring-boot:run",
            "group": "build"
        }
    ]
}

Like this:



Next

Create an example project