Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Spring Boot quick start code

I am new to Spring and Spring Boot, and I am trying it out. I am having trouble running the code sample from https://projects.spring.io/spring-boot/.

package hello;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

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

I issued mvn install and everything appears to be fine. But then I issued java -cp target/myArtifId-1.0-SNAPSHOT.jar hello.SampleController and ClassNotFoundException is thrown.

How do I run this code sample?

like image 450
Tripp Avatar asked Jul 15 '26 20:07

Tripp


2 Answers

As per spring boot documentation, you should be able to run your application with this command:

java -jar target/myArtifId-1.0-SNAPSHOT.jar

Spring Boot produces an executable jar, no need to specify a java class with a main method. That's also the reason why you can not include another class with a main method.

like image 182
François Maturel Avatar answered Jul 17 '26 15:07

François Maturel


I prefer to use run goal of Spring Boot Maven Plugin to compile and run it in a single command:

mvn spring-boot:run
like image 32
Pau Avatar answered Jul 17 '26 15:07

Pau