DEV Community

KenjiGoh
KenjiGoh

Posted on

Set up Spring Boot Java app with Maven in VS Code

1. Installation

2. Open settings.json VS Code

Add the following:

  "maven.terminal.customEnv": [
    {
      "environmentVariable": "JAVA_HOME",
      "value": "C:\\Program Files\\Java\\jdk-17.0.2"
    }
  ],
  "java.home": "C:\\Program Files\\Java\\jdk-17.0.2"
Enter fullscreen mode Exit fullscreen mode

3. Generate starter pack

4. mvn install:

If needed, close and Reopen your VS Code after configuring the settings.json

mvn clean install
Enter fullscreen mode Exit fullscreen mode

5. Add basic rest route:

You may refer to the Spring Quick Start Guide and copy the code:

package com.example.testapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication .class, args);
    }

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
      return String.format("Hello %s!", name);
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Run Springboot application

mvn spring-boot:run
Enter fullscreen mode Exit fullscreen mode

7. Visit localhost:8080

You may try http://localhost:8080/hello?name=yourName

8. Add more dependencies

Go to pom.xml file and right click > Add Starters

Image description

Image description

9. Build an executable JAR file - Build Once Run Anywhere

A single executable JAR file contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

mvn clean package
Enter fullscreen mode Exit fullscreen mode

This will create a target folder. Now you can simply run to run the app as well:

java -jar target/<project_name>-0.1.0.jar
Enter fullscreen mode Exit fullscreen mode

Jar file can run when double-click too. Just make sure to associate javaw.exe with jar file.

Image description

10. Can use BAT file instead

If .jar file does not work. You can create a .bat file. The batch file can be executed to invoke the jar, this method should definitely work. Add the following:

java -jar <project_name>.jar
Enter fullscreen mode Exit fullscreen mode

11. AutoGenerate Getters & Setters

Install Java Code Generators

Top comments (0)