3

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?

Tripp
  • 31
  • 1
  • if you are newbie to spring-boot, please refer this approach to kick start. http://stackoverflow.com/questions/39245732/java-lang-noclassdeffounderror-org-springframework-core-env-configurableenviron/39246493#39246493 – Praveen Kumar K S May 01 '17 at 10:22
  • You are missing the @SpringBootApplication annotation – Moshe Arad May 01 '17 at 19:16

2 Answers2

2

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.

François Maturel
  • 5,884
  • 6
  • 45
  • 50
  • 1
    For the OP's benefit: This is really about jars, but you can look at MANIFEST.MF and see what `Main-Class` is. In this case, it's `org.springframework.boot.loader.JarLauncher`. So the above command is equivalent to: `java -cp target/myArtifId-1.0-SNAPSHOT.jar org.springframework.boot.loader.JarLauncher` – flow2k May 04 '17 at 07:19
  • And after the Tomcat server starts, you can either 1) issue `curl localhost:8080`, or 2) point your browser to `localhost:8080`. Or if connecting over the network, you can of course point browser to `xx.xx.xx.xx:8080`. You should then see "Hello World!". – flow2k May 04 '17 at 07:28
1

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

mvn spring-boot:run
Pau
  • 14,917
  • 14
  • 67
  • 94