Demo Application
Learn about SpringBootApplication.
We'll cover the following
SpringBootApplication
The main class is specified by annotating it with @SpringBootApplication
. Create a file named “DemoApplication.groovy” in the com.example.demo
package, and put the following:
package com.example.demo
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class DemoApplication {
static void main(String[] args) {
SpringApplication.run DemoApplication, args //1
}
@Bean
Service sampleServier() { new SampleService() } //2
}
- The main method calls
SpringApplication.run
to start the application. - Beans can be created directly using the
@Bean
annotation on methods
The @SpringBootApplication
annotation tells Spring a number of things:
- To use auto-configuration.
- To use component scanning. Scanning all packages for classes annotated with Spring annotations.
- This class is a Java-based configuration class, so you can define beans here using the @Bean annotation on a method that returns a bean.
Alternatively, if you want to specify web-service mappings more directly, you can use the @Controller
and @RequestMapping
annotations like the following, hello/SampleController.java
:
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);
}
}
Of course, this would be a much smaller application. For larger projects, you should use the
@SpringBootApplication
approach.
Get hands-on with 1400+ tech skills courses.