Overview
Spring Boot is a rapid development framework based on the Spring framework. It provides features such as auto-configuration and starter dependencies, simplifying the development of Spring applications.
Core Features
1. Project Creation
Using Spring Initializr:
Visit https://start.spring.io/ or use an IDE plugin to create a project.
Using the CLI:
# 安装 Spring Boot CLI
brew install spring-boot
Create a project
spring init --dependencies=web,data-jpa,postgresql my-project
**Maven 项目结构**:
my-project/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/example/ │ │ │ └── MyApplication.java │ │ └── resources/ │ │ ├── application.properties │ │ └── application.yml │ └── test/ ├── pom.xml └── README.md
### 2. 自动配置
Spring Boot 通过自动配置简化了配置工作。
**application.yml**:
```yaml
spring:
application:
name: my-app
datasource:
url: jdbc:postgresql://localhost:5432/mydb
username: postgres
password: password
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
server:
port: 8080
application.properties:
spring.application.name=my-app
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server.port=8080
3. Dependency Injection
Using @Component:
@Component
public class UserService {
public String getUserName(Long id) {
return "User " + id;
}
}
Using @Service:
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
}
Using @Repository:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
List<User> findByNameContaining(String name);
}
4. Web Development
REST Controller:
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
}
Exception Handling:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
ErrorResponse error = new ErrorResponse(
HttpStatus.NOT_FOUND.value(),
ex.getMessage()
);
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}
5. Data Access
JPA Entity:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(unique = true, nullable = false)
private String email;
// Getters and Setters
}
Repository:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
List<User> findByNameContaining(String name);
@Query("SELECT u FROM User u WHERE u.email = :email")
Optional<User> findByEmailCustom(@Param("email") String email);
}
Service:
@Service
@Transactional
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User save(User user) {
return userRepository.save(user);
}
public Optional<User> findById(Long id) {
return userRepository.findById(id);
}
public List<User> findAll() {
return userRepository.findAll();
}
public void delete(Long id) {
userRepository.deleteById(id);
}
}
6. Configuration Management
@ConfigurationProperties:
@ConfigurationProperties(prefix = "app")
@Data
public class AppProperties {
private String name;
private String version;
private Database database;
@Data
public static class Database {
private String host;
private int port;
private String name;
}
}
Using Configuration:
app:
name: my-app
version: 1.0.0
database:
host: localhost
port: 5432
name: mydb
7. Security (Spring Security)
Dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic();
return http.build();
}
}
8. Testing
Unit Testing:
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Test
void testFindById() {
User user = userService.findById(1L)
.orElseThrow();
assertNotNull(user);
}
}
Integration Testing:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
Best Practices
1. Project Structure
com.example.myapp/
├── controller/ # 控制器
├── service/ # 服务层
├── repository/ # 数据访问层
├── entity/ # 实体类
├── dto/ # 数据传输对象
├── config/ # 配置类
└── exception/ # 异常类
2. Dependency Injection
- Prefer constructor injection
- Avoid using
@Autowiredfield injection - Use
@RequiredArgsConstructor(Lombok)
3. Exception Handling
- Use
@ControllerAdvicefor global exception handling - Define custom exception classes
- Return a unified error response format
4. Configuration Management
- Use
application.ymlinstead ofapplication.properties - Distinguish between development, testing, and production environment configurations
- Use
@ConfigurationPropertiesto bind configuration
Common Dependencies
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- PostgreSQL -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
Example Prompts
- "Create a REST API project using Spring Boot"
- "How do I use JPA for data access in Spring Boot?"
- "How do I configure a database connection in Spring Boot?"
- "How do I implement global exception handling in Spring Boot?"
- "How do I use Spring Security in Spring Boot?"