Spring Boot - Code Structure

Recommended Spring Boot Project code structure.

Typical Layout

A typical spring boot project layout:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
com
+- example
+- myapplication
+- Application.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java

It is recommended that the Application class that contains the main method to be located at the root package above other classes. This allows package scan to apply on your project. Application class is usually annotated with @SpringBootApplication annotation.

Application.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

}

@SpringBootApplication Annotation

@SpringBootApplication is a composite of three annotations

  • @EnableAutoConfiguration: attempts to automatically configure Spring application based on dependencies
  • @ComponentScan: allows spring beans for the application to be scanned
  • @Configuration: enables java base configuration

Dependency Injection Makes Easy

If you follow the typical Spring Boot Application structure, there is no need to use @ComponentScan to scan beans. @SpringBootApplication at the root package will scan all beans in the application. Just use @Autowired to wire the beans

Reference