← Назад к вопросам
Как реализовать базовое приложение на Spring Boot?
1.6 Junior🔥 91 комментариев
#Stream API и функциональное программирование
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Как реализовать базовое приложение на Spring Boot
Spring Boot — это фреймворк для быстрого создания production-ready Java приложений. Он упрощает конфигурацию Spring Framework и позволяет запустить приложение за несколько минут.
Шаг 1: Создание проекта
Можно использовать Spring Initializr или команду Maven:
mvn archetype:generate \
-DgroupId=com.example \
-DartifactId=my-app \
-DinteractiveMode=false
Или с Spring Boot CLI:
spring boot new --from https://start.spring.io my-app
Шаг 2: Зависимости в pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-app</artifactId>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<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>
<version>42.7.0</version>
</dependency>
<!-- Lombok для сокращения кода -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Тестирование -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Шаг 3: Основной класс приложения
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyAppApplication {
public static void main(String[] args) {
SpringApplication.run(MyAppApplication.class, args);
}
}
@SpringBootApplication — комбинирует три аннотации:
- @Configuration — определяет class как source конфигураций
- @EnableAutoConfiguration — включает auto-configuration
- @ComponentScan — сканирует компоненты в текущем пакете
Шаг 4: Конфигурация application.yml
spring:
application:
name: my-app
datasource:
url: jdbc:postgresql://localhost:5432/mydb
username: postgres
password: secret
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: validate
show-sql: false
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQL13Dialect
format_sql: true
jackson:
default-property-inclusion: non_null
server:
port: 8080
servlet:
context-path: /api/v1
logging:
level:
root: INFO
com.example: DEBUG
Шаг 5: Модель (Entity)
package com.example.domain;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String name;
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
}
Шаг 6: Repository (Data Access)
package com.example.infrastructure;
import com.example.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
boolean existsByEmail(String email);
}
Шаг 7: Service (Business Logic)
package com.example.application;
import com.example.domain.User;
import com.example.infrastructure.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User createUser(String email, String name) {
if (userRepository.existsByEmail(email)) {
throw new IllegalArgumentException("User already exists");
}
User user = User.builder()
.email(email)
.name(name)
.build();
return userRepository.save(user);
}
public User getUser(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("User not found"));
}
@Transactional
public User updateUser(Long id, String name) {
User user = getUser(id);
user.setName(name);
return userRepository.save(user);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
Шаг 8: REST Controller
package com.example.presentation;
import com.example.application.UserService;
import com.example.domain.User;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping
public ResponseEntity<User> createUser(
@RequestParam String email,
@RequestParam String name
) {
User user = userService.createUser(email, name);
return ResponseEntity.status(201).body(user);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
return ResponseEntity.ok(userService.getUser(id));
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(
@PathVariable Long id,
@RequestParam String name
) {
return ResponseEntity.ok(userService.updateUser(id, name));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}
Шаг 9: Запуск приложения
# Development mode
mvn spring-boot:run
# Build и запуск JAR
mvn clean package
java -jar target/my-app-1.0.0.jar
Приложение будет доступно на http://localhost:8080/api/v1
Шаг 10: Тестирование
package com.example;
import com.example.application.UserService;
import com.example.infrastructure.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@Test
void testCreateUser() {
var user = userService.createUser("test@example.com", "John");
assert user.getId() != null;
assert user.getEmail().equals("test@example.com");
}
}
Структура проекта
my-app/
├── src/main/java/com/example/
│ ├── MyAppApplication.java // Main класс
│ ├── domain/
│ │ └── User.java // Entity
│ ├── infrastructure/
│ │ └── UserRepository.java // Repository
│ ├── application/
│ │ └── UserService.java // Service
│ └── presentation/
│ └── UserController.java // REST Controller
├── src/main/resources/
│ └── application.yml // Конфигурация
├── src/test/java/com/example/
│ └── UserServiceTest.java // Тесты
└── pom.xml // Maven config
Key Features Spring Boot
- Auto-configuration — автоматическая настройка бинов
- Embedded servers — Tomcat встроен в JAR
- Production-ready — metrics, health checks из коробки
- Стартеры — готовые наборы зависимостей
Это базовая setup для Spring Boot приложения. Для production нужны дополнительные элементы: security, async processing, caching, API documentation.