Разработка серверной части на Java с применением Spring Framework

Раздел: Java веб-разработка -> Spring

Spring приложение на Java: базовый каркас и альтернативные подходы

Основной вариант для большинства задач: Spring Boot с Maven. Такой каркас даёт встроенный сервер, автоконфигурацию и управление зависимостями. Ниже показан минимальный REST-сервис.

Файл pom.xml с зависимостями

<project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd'>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.2</version>
    <relativePath/>
  </parent>
  <groupId>com.example</groupId>
  <artifactId>demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <java.version>21</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </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>

Java spring приложение (spring приложение на java)

Главный класс приложения

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);
    }
}

REST-контроллер

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/api/hello")
    public String hello(@RequestParam(defaultValue = "Spring") String name) {
        return "Hello, " + name + "!";
    }
}

Настройки в application.yml

server:
  port: 8080
spring:
  application:
    name: demo-app

Запуск и проверка

mvn spring-boot:run
curl 'http://localhost:8080/api/hello?name=Java'
Hello, Java!

Тест контроллера

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(HelloController.class)
class HelloControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    void helloReturnsGreeting() throws Exception {
        mockMvc.perform(get("/api/hello").param("name", "Test"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello, Test!"));
    }
}
BUILD SUCCESS

Как собрать Spring приложение без Spring Boot через XML конфигурацию?

Этот вариант встречается в legacy WAR проектах и в средах, где уже есть внешний сервлет-контейнер. Конфигурация разделяется между web.xml и applicationContext.xml.

<web-app xmlns='http://xmlns.jcp.org/xml/ns/javaee'
         xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
         xsi:schemaLocation='http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd'
         version='4.0'>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
<beans xmlns='http://www.springframework.org/schema/beans'
       xmlns:context='http://www.springframework.org/schema/context'
       xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
       xsi:schemaLocation='http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd'>
  <context:component-scan base-package='com.example.legacy'/>
</beans>
package com.example.legacy;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LegacyController {
    @GetMapping("/legacy/hello")
    @ResponseBody
    public String hello() {
        return "Legacy Spring MVC";
    }
}

Типичная ошибка: исключение No WebApplicationContext found. Причина в отсутствии ContextLoaderListener или в неверном contextConfigLocation. Проверка выполняется по логам старта контейнера и по наличию слушателя в web.xml.

Как настроить Spring MVC без автоконфигурации Spring Boot?

Java-based конфигурация подходит для встроенного Tomcat или Jetty без Spring Boot. Вместо XML применяются классы WebApplicationInitializer и WebMvcConfigurer.

package com.example.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}
package com.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.example")
public class RootConfig {
}
package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.example.web")
public class WebConfig {
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

Ошибка 404 при корректном контроллере часто связана с компонентным сканированием. Пакет контроллера должен попадать в basePackages для WebConfig. Второй источник проблемы: отсутствие @EnableWebMvc.

Как запустить Spring приложение в Docker?

Docker полезен для воспроизводимой среды. Для Spring Boot применяется многоступенчатая сборка: Maven собирает jar, затем JRE запускает приложение.

FROM maven:3.9.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn package -DskipTests

FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t demo-app .
docker run --rm -p 8080:8080 demo-app
Tomcat started on port 8080

Контейнер может завершиться при нехватке памяти. Для JVM полезны параметры -XX:MaxRAMPercentage=75.0 и -XX:+UseContainerSupport. Порт 8080 внутри контейнера должен совпадать с server.port.

Как разделить конфигурацию по профилям и переменным окружения?

Профили позволяют держать разные настройки для dev, test и prod. Значения можно переопределять переменными окружения без пересборки jar.

# application-dev.yml
spring:
  datasource:
    url: jdbc:h2:mem:devdb
    username: sa
    password:
# application-prod.yml
spring:
  datasource:
    url: ${DB_URL}
    username: ${DB_USER}
    password: ${DB_PASSWORD}
java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
SPRING_PROFILES_ACTIVE=prod DB_URL=jdbc:postgresql://db/app java -jar demo.jar

Если профиль не активирован, Spring использует application.yml без специализированных значений. Ошибка с пустым DB_URL возникает при отсутствии переменной окружения. Диагностика выполняется через /actuator/env или лог активных профилей.

Как подключить базу данных и JPA в Spring приложении?

Spring Data JPA уменьшает объём кода для CRUD. Ниже пример сущности, репозитория, сервиса и контроллера.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>
package com.example.demo;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
}
package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {
}
package com.example.demo;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class BookService {
    private final BookRepository repository;

    public BookService(BookRepository repository) {
        this.repository = repository;
    }

    public Book create(String title) {
        Book book = new Book();
        book.setTitle(title);
        return repository.save(book);
    }
}
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BookController {
    private final BookService service;

    public BookController(BookService service) {
        this.service = service;
    }

    @PostMapping("/books")
    public Book create(@RequestParam String title) {
        return service.create(title);
    }

    @GetMapping("/books")
    public java.util.List<Book> all() {
        return service.all();
    }
}
spring:
  datasource:
    url: jdbc:h2:mem:books
    driver-class-name: org.h2.Driver
  jpa:
    hibernate:
      ddl-auto: create-drop
    show-sql: true
[{"id":1,"title":"Spring in Action"}]

Режим ddl-auto=update в production может привести к неожиданным изменениям схемы. Для управляемых миграций применяется Flyway или Liquibase. Ошибка LazyInitializationException появляется при доступе к ленивой связи вне транзакции.

Расширенные примеры для Spring приложения на Java

Пример 1: Обработка ошибок через ProblemDetail

Класс @RestControllerAdvice возвращает ProblemDetail, который соответствует RFC 7807. Такой формат удобен для API.

Пример
package com.example.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ApiExceptionHandler {
    @ExceptionHandler(UserNotFoundException.class)
    public ProblemDetail handleUserNotFound(UserNotFoundException ex) {
        ProblemDetail detail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        detail.setTitle("User not found");
        detail.setProperty("userId", ex.getUserId());
        return detail;
    }
}
Пример
package com.example.demo;

public class UserNotFoundException extends RuntimeException {
    private final Long userId;

    public UserNotFoundException(Long userId) {
        super("User " + userId + " not found");
        this.userId = userId;
    }

    public Long getUserId() { return userId; }
}
Пример
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @GetMapping("/api/users/{id}")
    public String user(@PathVariable Long id) {
        throw new UserNotFoundException(id);
    }
}
HTTP/1.1 404
Content-Type: application/problem+json

{
  "type": "about:blank",
  "title": "User not found",
  "status": 404,
  "detail": "User 42 not found",
  "instance": "/api/users/42",
  "userId": 42
}

Пример 2: Собственный HealthIndicator

Actuator собирает состояние компонентов. Собственный индикатор проверяет внешний ресурс, например очередь.

Пример
package com.example.demo;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class QueueHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        boolean available = checkQueue();
        if (available) {
            return Health.up()
                    .withDetail("queue", "ok")
                    .withDetail("pending", 12)
                    .build();
        }
        return Health.down()
                .withDetail("queue", "unreachable")
                .build();
    }

    private boolean checkQueue() {
        return true;
    }
}
Пример
management:
  endpoints:
    web:
      exposure:
        include: health,info
  endpoint:
    health:
      show-details: always
{
  "status": "UP",
  "components": {
    "queue": {
      "status": "UP",
      "details": {
        "queue": "ok",
        "pending": 12
      }
    }
  }
}

Пример 3: Асинхронный метод с @Async

Асинхронность помогает вынести долгую операцию из HTTP-потока. Нужен @EnableAsync и собственный executor.

Пример
package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean(name = "reportExecutor")
    public Executor reportExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(4);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("report-");
        executor.initialize();
        return executor;
    }
}
Пример
package com.example.demo;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Service
public class ReportService {
    @Async("reportExecutor")
    public CompletableFuture<String> buildReport(Long userId) {
        String result = "report for " + userId + " on " + Thread.currentThread().getName();
        return CompletableFuture.completedFuture(result);
    }
}
Пример
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

@RestController
public class ReportController {
    private final ReportService service;

    public ReportController(ReportService service) {
        this.service = service;
    }

    @GetMapping("/reports/{userId}")
    public CompletableFuture<String> report(@PathVariable Long userId) {
        return service.buildReport(userId);
    }
}
report for 7 on report-1

Пример 4: Условные бины через @ConditionalOnProperty

Такой приём даёт выбор реализации через настройки. Код не зависит от конкретного платёжного шлюза.

Пример
package com.example.demo;

public interface PaymentGateway {
    String pay(long amount);
}
Пример
package com.example.demo;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty(name = "payment.provider", havingValue = "stripe")
public class StripeGateway implements PaymentGateway {
    @Override
    public String pay(long amount) {
        return "stripe:" + amount;
    }
}
Пример
package com.example.demo;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty(name = "payment.provider", havingValue = "paypal")
public class PaypalGateway implements PaymentGateway {
    @Override
    public String pay(long amount) {
        return "paypal:" + amount;
    }
}
Пример
payment:
  provider: stripe
PaymentGateway: StripeGateway

Пример 5: Динамические JPA Specification

Specification подходит для фильтров с необязательными параметрами. Запрос собирается из условий.

Пример
package com.example.demo;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String category;
    private Integer price;

    public String getName() { return name; }
    public String getCategory() { return category; }
    public Integer getPrice() { return price; }
}
Пример
package com.example.demo;

import org.springframework.data.jpa.domain.Specification;

public class ProductSpecifications {
    public static Specification<Product> hasName(String name) {
        return (root, query, cb) -> name == null ? null : cb.equal(root.get("name"), name);
    }

    public static Specification<Product> hasCategory(String category) {
        return (root, query, cb) -> category == null ? null : cb.equal(root.get("category"), category);
    }

    public static Specification<Product> priceLessThan(Integer max) {
        return (root, query, cb) -> max == null ? null : cb.lessThan(root.get("price"), max);
    }
}
Пример
package com.example.demo;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
}
Пример
package com.example.demo;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ProductController {
    private final ProductRepository repository;

    public ProductController(ProductRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/products")
    public List<Product> search(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) Integer maxPrice) {
        Specification<Product> spec = Specification.where(ProductSpecifications.hasName(name))
                .and(ProductSpecifications.hasCategory(category))
                .and(ProductSpecifications.priceLessThan(maxPrice));
        return repository.findAll(spec);
    }
}
Hibernate: select ... from product where name=? and category=? and price<?

Пример 6: Testcontainers и PostgreSQL

Testcontainers поднимает реальную базу в тесте. Это уменьшает расхождение между тестовой и рабочей средой.

Пример
<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>postgresql</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>junit-jupiter</artifactId>
  <scope>test</scope>
</dependency>
Пример
package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@SpringBootTest
@Testcontainers
class ProductRepositoryTest {
    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @DynamicPropertySource
    static void props(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Test
    void contextLoads() {
    }
}
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

Пример 7: WebClient с таймаутом и retry

WebClient применяется в реактивном стеке. Настройка timeout и retry делает вызовы внешних API устойчивее.

Пример
package com.example.demo;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Configuration
public class WebClientConfig {
    @Bean
    public WebClient webClient() {
        HttpClient httpClient = HttpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000)
                .responseTimeout(Duration.ofSeconds(3))
                .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(3, TimeUnit.SECONDS)));

        return WebClient.builder()
                .baseUrl("https://api.example.com")
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }
}
Пример
package com.example.demo;

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.util.retry.Retry;

import java.time.Duration;

@Service
public class ExternalApiService {
    private final WebClient webClient;

    public ExternalApiService(WebClient webClient) {
        this.webClient = webClient;
    }

    public String fetchStatus() {
        return webClient.get()
                .uri("/status")
                .retrieve()
                .bodyToMono(String.class)
                .retryWhen(Retry.backoff(3, Duration.ofMillis(200)))
                .block(Duration.ofSeconds(5));
    }
}
Response: {"ok":true}

Пример 8: Кастомный аргумент резолвер

HandlerMethodArgumentResolver извлекает данные из запроса и передаёт их в параметр контроллера.

Пример
package com.example.demo;

public record CurrentUser(String name) {
}
Пример
package com.example.demo;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class CurrentUserResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) {
        String user = webRequest.getHeader("X-User");
        return new CurrentUser(user == null ? "anonymous" : user);
    }
}
Пример
package com.example.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    private final CurrentUserResolver resolver;

    public WebConfig(CurrentUserResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(resolver);
    }
}
Пример
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProfileController {
    @GetMapping("/profile")
    public String profile(CurrentUser user) {
        return "Authenticated user: " + user.name();
    }
}
Authenticated user: alice

Пример 9: События приложения

ApplicationEventPublisher разделяет бизнес-логику и побочные действия. Слушатель может работать синхронно или асинхронно.

Пример
package com.example.demo;

public record OrderCreatedEvent(Long orderId) {
}
Пример
package com.example.demo;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
    private final ApplicationEventPublisher publisher;

    public OrderService(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    public void create(Long orderId) {
        publisher.publishEvent(new OrderCreatedEvent(orderId));
    }
}
Пример
package com.example.demo;

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class OrderListener {
    @EventListener
    public void onOrderCreated(OrderCreatedEvent event) {
        System.out.println("Order created: " + event.orderId());
    }
}
Order created: 10

Spring приложение на Java - comments

En
Java spring приложение (java)