본문 바로가기
spring

Spring Boot 3.0 변경 내용

by tango0415 2023. 1. 29.

springboot 3.0

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Release-Notes

주관적인 주요 변경 사항

  • 최소 Java 17부터 사용가능
  • GraalVM 기반의 native image 생성을 정식 지원
  • Micrometer, Micrometer Tracing 모니터링 기능 강화
  • Java EE to Jakarta EE 마이그레이션 필요
  • Improved @ConstructorBinding Detection

GraalVM ?

https://docs.spring.io/spring-boot/docs/3.0.0/reference/html/native-image.html#native-image

AOT 과정을 통해 빌드된 독립적으로 실행 가능한 프로그램이다
JVM과 비교해서 빌드 시간이 길지만, 메모리 사용량이 적고 실행 속도가 빠르다
cross-compilation을 지원하지는 않지만, JVM 없이도 실행 가능하다

docker image로도 빌드할 수 있고, native image로도 빌드 할 수 있다

mvn -Pnative spring-boot:build-image
gradle bootBuildImage
docker run --rm -p 8080:8080 docker.io/library/myproject:0.0.1-SNAPSHOT

mvn -Pnative native:compile
gradle nativeCompile
target/myproject

JVM과의 차이점

  • main entry point에서부터 정적 분석을 실행한다
  • image 생성 시점에 도달할 수 없는 코드는 실행 파일에 포함되지 않는다
  • dynamic 요소에 대해서 알지못하고, reflection, resources, serialization, dynamic proxies에 대해서 알려주는 무언가가 있어야 한다
  • classpath는 고정된다
  • laza class loading을 지원하지 않는다. 모든 것은 실행 시점에 메모리에 로딩된다
  • 몇몇 제약 사항이 존재한다

Java EE ? Jakarte EE ?

용어정리

  • Java EE
    • Java Platform, Enterprise Edition
  • J2EE
    • Java 2 Platform Enterprise Edition
  • JCP
    • Java Community Process
  • JSR
    • Java Specification Request

자바EE는 1999년 썬 마이크로시스템즈가 발표한 분산 애플리케이션 개발 목적의 산업 표준 플랫폼
2017년에 자바EE 8을 마지막으로 비영리 단체 이클립스 재단에 자바EE 프로젝트를 이관
이클립스 재단에서는 이관은 받았지만, 자바 상표권이 없기 때문에 자카르타라는 이름을 사용하기 시작

출처:  https://www.samsungsds.com/kr/insights/java_jakarta.html

Log4j2 Enhancements

https://docs.spring.io/spring-boot/docs/3.0.0/reference/html/features.html#features.logging.log4j2-extensions

  • Profile-specific Configuration
  • Environment Properties Lookup
  • Log4j2 System Properties

새로운 기능을 사용하기 위해서는 log4j2.xml을 사용하는 것 대신 log4j2-spring.xml이나 logging.config property를 사용해야 한다. log4j2.xml 설정 파일은 너무 빨리 로드된다

빌드 결과물에 org.apache.logging.log4j:log4j-spring-boot이 포함되지 않도록 해야한다

log4j-spring.xml 파일 내부에서 profile, 환경변수, 시스템 변수를 사용할 수 있다

<SpringProfile name="staging">
    <!-- configuration to be enabled when the "staging" profile is active -->
</SpringProfile>

<SpringProfile name="dev | staging">
    <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</SpringProfile>

<SpringProfile name="!production">
    <!-- configuration to be enabled when the "production" profile is not active -->
</SpringProfile>

<Properties>
    <Property name="applicationName">${spring:spring.application.name}</property>
</Properties>

Log4j Configuring - System Properties

Improved @ConstructorBinding Detection

@ConstructorBinding
@ConfigurationProperties(prefix = "aerospike")
data class AerospikeConfigurationProperties(
    val hosts: String,
    val namespace: String,
    val readTimeout: Int,
    val writeTimeout: Int,
)

@ConfigurationProperties, @ConstructorBinding을 같이 사용했었는데, 이제 생성자가 1개만 있는 경우에는 @ConstructorBinding을 생략할 수 있다

Micrometer Updates

Auto-configuration for Micrometer Observation API

Micrometer는 Spring Application에서 메트릭을 남기기 위한 facade이다.
마치 Logging facade (SLF4j) 처럼

Observation, ObservationRegistry, ObservationHandler, Observation.Context, ObservationFilter, ObservationConvention, GlobalObservationConvention, DefaultTaxObservationConvention, @Observed(name = "greetingService") 등 여러가지 기능이 지원된다

분산환경에서의 tracing을 위해서 Observation 객체를 생성할 수 있다. 생성시 ObservationRegistry에 등록한다

Auto-configuration for Micrometer Tracing

Metric 뿐만 아니라 Tracing에 대해서도 auto-configure를 지원한다. Brave, OpenTelemetry, Zipkin Wavefront

kubernetest 환경이라면 분산 tracing 도구로 istio, jaeger 등도 같이 사용할 수 있겠지만,
그렇지 않다고 하더라도 zipkin 같은 것을 유용하게 사용할 수 있을 것 같다

Auto-configuration for Micrometer’s OtlpMeterRegistry

classpath에 io.micrometer:micrometer-registry-otlp이 존재한다면 Otlp (OpenTelemetry Protocol) MeterResigry에 대한 Auto-configuration이 지원된다.
property 설정은 이런 경로를 사용한다. management.otlp.metrics.export.*

출처:  https://binux.tistory.com/151

Prometheus Support

Auto-Configuration for Prometheus Exemplars

Tracer, Prometheus가 classpath에 존재한다면 SpanContextSupplier에 대한 Auto-configuration이 지원된다.
Prometheus를 연동할때도 동일한 trace ID, span ID를 사용할 수 있도록 지원한다

Making a PUT to Prometheus Push Gateway on Shutdown

management.prometheus.metrics.export.pushgateway.shutdown-operation Property에 post를 쓰는 것은 deprecated 되었고, put을 사용해야 합니다.

More Flexible Auto-configuration for Spring Data JDBC

Spring Data JDBC 관련 Bean 설정이 좀 더 유연해집니다.
아래와 같은 Type의 Bean을 재설정함으로써 기존의 Bean을 쉽게 대체할 수 있습니다.

  • org.springframework.data.jdbc.core.JdbcAggregateTemplate
  • org.springframework.data.jdbc.core.convert.DataAccessStrategy
  • org.springframework.data.jdbc.core.convert.JdbcConverter
  • org.springframework.data.jdbc.core.convert.JdbcCustomConversions
  • org.springframework.data.jdbc.core.mapping.JdbcMappingContext
  • org.springframework.data.relational.RelationalManagedTypes
  • org.springframework.data.relational.core.dialect.Dialect

Enabling Async Acks with Apache Kafka

Kafka의 async acks 기능을 활성화하기 위해서 spring.kafka.listener.async-acks Property가 추가되었습니다.

Elasticsearch Java Client

Elasticsearch 8.3 버전을 위한 새로운 Property가 기존에 사용하던 spring.elasticsearch.* 경로에 추가되었습니다.

Auto-configuration of JdkClientHttpConnector

Apache HTTP client가 없거나, Reactor, Jettry의 reactive client Netty가 configure 되어 있다면, JdkClientHttpConnector가 Auto-Configure 됩니다.
WebClient의 ClientHttpConnector의 구현체로 사용될 수 있다.

WebClient 내부에선 HTTP 클라이언트 라이브러리에 처리를 위임한다.
디폴트는 Reactor Nettry를 사용하고, Jetty reactive HttpClient를 기본으로 제공하며,
다른 라이브러리는 ClientHttpConnector에 등록할 수 있다
출처: https://godekdls.github.io/Reactive%20Spring/webclient/

@SpringBootTest with Main Methods

SpringBoot Application의 Main 메서드는 보통은 SpringApplication 을 실행시키는 것 외에는 별로 하는일이 없다.
하지만 아래와 같이 어떠한 로직이 존재하는 경우가 있을 수 있는데, 이런 경우 @SpringBootTest를 사용할때 main 메서드를 실행할지 안할지를 선택할 수 있다.

@SpringBootTest(useMainMethod = UseMainMethod.ALWAYS)

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(MyApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.setAdditionalProfiles("myprofile");
        application.run(args);
    }

}

Miscellaneous

  • 실행시 Hostname이 로깅되지 않는다. 이는 network lookup을 수행하지 않음으로써 실행 시간을 더 빠르게 한다
  • Java의 SecurityManager에 대한 지원은 JDK에서 더 이상 사용되지 않기 때문에 제거되었습니다.
  • Spring Framework의 CommonsMultipartResolver에 대한 지원이 Spring Framework 6에서 제거된 후 제거되었습니다.
  • spring.mvc.ignore-default-model-on-redirect는 Spring Framework 변경 사항에 맞추기 위해 더 이상 사용되지 않습니다.
  • WebJars resource handler path pattern은 spring.mvc.webjars-path-pattern 또는 spring.webflux.webjars-path-pattern을 사용하여 지정할 수 있습니다.
  • Tomcat의 신뢰할 수 있는 proxy IP 설정을 server.tomcat.remoteip.trusted-proxies를 사용하여 구성할 수 있습니다.
  • ValidationConfigurationCustomizer Bean을 통해서 Bean Validation Configuration을 지정할 수 있습니다
  • Log4j2의 Log4jBridgeHandler는 이제 SLF4J를 통한 라우팅이 아닌 JUL 기반으로 Log4j2로 라우팅합니다
  • MeterBinder 인터페이스를 구현하는 Bean은 이제 모든 singleton Bean이 초기화된 후에만 MeterRegistry에 바인딩됩니다
  • Brave 및 OpenTelemetry용 SpanCustomizer 빈은 이제 Auto-configure 됩니다
  • Micrometer의 JvmCompilationMetrics는 이제 자동 구성됩니다
  • DiskSpaceHealthIndicator는 이제 로그 메시지의 경로와 상태 세부 정보를 포함합니다
  • DataSourceBuilder는 이제 wrapped DataSource에서 파생될 수 있습니다
  • spring.data.mongodb.additional-hosts 속성을 사용하여 MongoDB에 대해 여러 호스트를 구성할 수 있습니다
  • Elasticsearch의 socketKeepAlive 속성은 spring.elasticsearch.socket-keep-alive 속성을 사용하여 구성할 수 있습니다
  • spring-rabbit-stream을 사용할 때 spring.rabbitmq.listener.type이 스트림인지 여부에 관계없이 RabbitStreamTemplate 및 환경이 자동으로 구성됩니다
  • 기존 Kafka Topic은 spring.kafka.admin.modify-topic-configs를 사용하여 수정할 수 있습니다
  • WebDriverScope 및 WebDriverTestExecutionListener가 공개되어 사용자 지정 테스트 설정에서 WebDriver를 쉽게 사용할 수 있습니다

Deprecations in Spring Boot 3.0

  • @ConstructorBinding이 org.springframework.boot.context.properties 패키지에서 org.springframework.boot.context.properties.bind로 재배치되었습니다.
  • JsonMixinModule 스캐닝 기반 생성자는 더 이상 사용되지 않습니다.
  • ClientHttpRequestFactorySupplier를 ClientHttpRequestFactories로 바꿔야 합니다.
  • cookie comment 속성은 더 이상 지원되지 않습니다.
  • RestTemplateExchangeTagsProvider, WebClientExchangeTagsProvider, WebFluxTagsProvider, WebMvcTagsProvider 및 관련 클래스는 ObservationConvention과 동등한 항목으로 대체되었습니다.
  • HealthContributor @Configuration 기본 클래스의 no-args 생성자는 더 이상 사용되지 않습니다.
  • DefaultTestExecutionListenersPostProcessor 및 SpringBootDependencyInjectionTestExecutionListener는 Spring Framework의 ApplicationContextFailureProcessor를 위해 더 이상 사용되지 않습니다.
  • management.metrics.export. 속성은 더 이상 사용되지 않으며 management..metrics.export로 대체됩니다.
  • @AutoConfigureMetrics는 @AutoConfigureObservability를 위해 더 이상 사용되지 않습니다.

'spring' 카테고리의 다른 글

Spring Boot 2.4 변경 내용  (0) 2021.01.19
xml to java config 기반으로 전환  (0) 2020.08.16
Spring JDK Dynamic Proxy vs CGLIB 차이점  (0) 2020.06.14