Sub topic 9
The main class and @SpringBootApplication
This chapter assumes you can read basic Java and annotations, and that you know what a Spring bean and dependency injection are. It also assumes you have a generated project like the one from the earlier chapters. Here you will see what the generated main class does line by line, what @SpringBootApplication stands for, and which mistakes it causes most often.
The generated entry point
Spring Initializr produces one class with a main method. Everything else in the application is started from it.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}The class has two parts. The annotation tells Spring how to build the application. The main method starts that process.
SpringApplication.run does the following:
- It creates an application context, which is the container that holds your beans.
- It reads the class you passed in as the primary configuration source.
- It loads configuration such as
application.propertiesinto the environment. - It creates the beans, applying auto-configuration along the way.
- If the web starter is on the classpath, it starts the embedded server.
- It returns the running context.
The args array is passed along so that command-line arguments such as --server.port=9090 become configuration properties.
What @SpringBootApplication really is
@SpringBootApplication is a convenience annotation. It is meta-annotated with three other annotations, so putting it on a class has the same effect as putting all three there.
| Annotation | What it does |
|---|---|
| `@SpringBootConfiguration` | Marks the class as a configuration class. It is a specialization of `@Configuration`, so you can declare `@Bean` methods in the main class. |
| `@EnableAutoConfiguration` | Turns on auto-configuration. Boot inspects the classpath and your existing beans and registers the beans it thinks you need. |
| `@ComponentScan` | Scans a package and its sub-packages for `@Component`, `@Service`, `@Repository`, `@Controller`, `@RestController` and similar stereotypes. |
This main class behaves the same as the generated one:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}Nobody writes it this way in practice. It is useful for understanding, and for the rare case where you want only part of the behavior. For example, you can drop @EnableAutoConfiguration and import specific configuration classes yourself.
The real @ComponentScan on @SpringBootApplication also carries two exclude filters. TypeExcludeFilter lets test slices (such as @WebMvcTest) hide components that do not belong in the slice. AutoConfigurationExcludeFilter keeps auto-configuration classes from being picked up by component scanning, because they must be loaded through the auto-configuration mechanism only.
Component scanning and the package rule
@ComponentScan with no arguments scans the package of the class that carries it, plus all sub-packages. This is why the generated HelloController works without any registration: it sits in com.example.demo, the same package as DemoApplication.
A controller in a sibling package is not found:
com.example.demo.DemoApplicationis the main class.com.example.demo.web.HelloControlleris scanned, because it is a sub-package.com.example.shared.AuditServiceis not scanned, because it is outsidecom.example.demo.
When this goes wrong there is no startup error for the missing controller. The application starts, and the endpoint returns 404. A missing service that another bean needs does fail at startup, with a NoSuchBeanDefinitionException or an "unsatisfied dependency" message.
There are two fixes. The better one is to move the main class up to the common root package, so that everything lives below it. The other is to widen the scan explicitly:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.shared"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}scanBasePackageClasses takes marker classes instead of strings, which survives package renames when you refactor.
Controlling auto-configuration
@EnableAutoConfiguration is driven by conditions. Each auto-configuration class declares conditions such as "only if class X is on the classpath" (@ConditionalOnClass) or "only if the user has not defined a bean of this type" (@ConditionalOnMissingBean). The second condition is why your own bean always wins over Boot's default: you define a bean, and the matching auto-configuration steps back.
Sometimes you want to switch an auto-configuration off completely. A typical case is a project that has a JDBC driver on the classpath for a later chapter but has no database configured yet, so Boot fails trying to build a DataSource. You can exclude it on the annotation:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}This compiles only when the class is on the compile classpath, which means a JDBC or data starter must be present. If the class may be absent, use excludeName with the fully qualified class name as a string. The same exclusion can be written as a property, with no code change:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationTo see what Boot decided, start the application with --debug. It prints a conditions report that lists which auto-configurations matched and which did not, with the reason for each.
Configuration classes and @Bean methods
Because @SpringBootApplication includes @SpringBootConfiguration, you can declare beans directly in the main class:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public String greeting() {
return "Hello from a bean";
}
}This works, but it is a habit to avoid in larger projects. The main class is the root of scanning, and it is also picked up by test utilities. Keeping it small and putting beans in dedicated @Configuration classes makes tests easier to slice.
By default @SpringBootApplication uses full @Configuration proxying, so calls between @Bean methods return the same singleton. Setting proxyBeanMethods = false skips the proxy and starts slightly faster. Do it only when no @Bean method calls another one directly.
Using and customizing SpringApplication
SpringApplication.run is a static shortcut. When you need to change startup behavior, create an instance instead. You can also keep the returned context to inspect it:
package com.example.demo;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(DemoApplication.class);
app.setBannerMode(Banner.Mode.OFF);
ConfigurableApplicationContext context = app.run(args);
System.out.println("Beans: " + context.getBeanDefinitionCount());
}
}Many of these settings can also be set through properties, for example spring.main.banner-mode=off. Prefer properties when you can, because they can differ per environment without a rebuild.
For a web application, run does not block the main thread in your own code. The server threads keep the JVM alive after main returns, so the println above runs right after startup.
Common errors
- Endpoint returns 404 but the app starts. The controller is outside the scanned packages. Check the package statement against the main class.
NoSuchBeanDefinitionExceptionfor your own service. The same cause, or a missing stereotype annotation such as@Service.- Startup fails with "Failed to configure a DataSource". A database starter is on the classpath without connection properties. Add the properties, remove the dependency, or exclude the auto-configuration.
- Two classes annotated with
@SpringBootApplication. Scanning can find the second one as a configuration class, and tests may fail to choose the right one. Keep exactly one. - Main class in the default package. Move it into a named package.
Exercise
Your application starts without errors, but GET /orders returns 404. The controller is com.example.orders.OrderController, annotated with @RestController. The main class is com.example.demo.DemoApplication with a plain @SpringBootApplication. What is the cause, and what are two ways to fix it?
Show answer
The controller is in com.example.orders, which is not inside com.example.demo, so component scanning never registers it. Fix 1: move the main class to the common root package com.example so both packages are scanned. Fix 2: keep the main class where it is and set @SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.orders"}).
Exercise
Name the three annotations that @SpringBootApplication combines, and say which one makes your own @Bean replace a Boot default.
Show answer
@SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan. The replacement comes from @EnableAutoConfiguration: auto-configuration classes use @ConditionalOnMissingBean, so they back off when you have defined a bean of the same type.