반응형
Jake Seo
제이크서 위키 블로그
Jake Seo
전체 방문자
오늘
어제
  • 분류 전체보기 (715)
    • 일상, 일기 (0)
    • 백준 문제풀이 (1)
    • 릿코드 문제풀이 (2)
    • 알고리즘 이론 (10)
      • 기본 이론 (2)
      • 배열과 문자열 (8)
    • 데이터베이스 (15)
      • Planet Scale (1)
      • MSSQL (9)
      • 디비 기본 개념 (1)
      • SQLite 직접 만들어보기 (4)
    • 보안 (7)
    • 설계 (1)
    • 네트워크 (17)
      • HTTP (9)
      • OSI Layers (5)
    • 회고 (31)
      • 연간 회고 (2)
      • 주간 회고 (29)
    • 인프라 (52)
      • 도커 (12)
      • AWS (9)
      • 용어 (21)
      • 웹 성능 (1)
      • 대규모 서비스를 지탱하는 기술 (9)
    • 깃 (7)
    • 빌드 도구 (7)
      • 메이븐 (6)
      • 그레이들 (0)
    • Java (135)
      • 이펙티브 자바 (73)
      • 자바 API (4)
      • 자바 잡지식 (30)
      • 자바 디자인 패턴 (21)
      • 톰캣 (Tomcat) (7)
    • 프레임워크 (64)
      • next.js (14)
      • 스프링 프레임워크 (28)
      • 토비의 스프링 (6)
      • 스프링 부트 (3)
      • JPA (Java Persistence API) (5)
      • Nest.js (8)
    • 프론트엔드 (48)
      • 다크모드 (1)
      • 노드 패키지 관리 매니저 (3)
      • CSS (19)
      • Web API (11)
      • tailwind-css (1)
      • React (5)
      • React 새 공식문서 요약 (1)
      • HTML (Markup Language) (5)
    • 자바스크립트 (108)
      • 모던 자바스크립트 (31)
      • 개념 (31)
      • 정규표현식 (5)
      • 코드 스니펫 (1)
      • 라이브러리 (6)
      • 인터뷰 (24)
      • 웹개발자를 위한 자바스크립트의 모든 것 (6)
      • 팁 (2)
    • Typescript (49)
    • 리눅스와 유닉스 (10)
    • Computer Science (1)
      • Compiler (1)
    • IDE (3)
      • VSCODE (1)
      • IntelliJ (2)
    • 세미나 & 컨퍼런스 (1)
    • 용어 (개발용어) (16)
      • 함수형 프로그래밍 용어들 (1)
    • ORM (2)
      • Prisma (2)
    • NODEJS (2)
    • cypress (1)
    • 리액트 네이티브 (React Native) (31)
    • 러스트 (Rust) (15)
    • 코틀린 (Kotlin) (4)
      • 자바에서 코틀린으로 (4)
    • 정규표현식 (3)
    • 구글 애널리틱스 (GA) (1)
    • SEO (2)
    • UML (2)
    • 맛탐험 (2)
    • 리팩토링 (1)
    • 서평 (2)
    • 소프트웨어 공학 (18)
      • 테스팅 (16)
      • 개발 프로세스 (1)
    • 교육학 (1)
    • 삶의 지혜, 통찰 (1)
    • Chat GPT (2)
    • 쉘스크립트 (1)
    • 컴파일 (2)
    • Dart (12)
    • 코드팩토리의 플러터 프로그래밍 (4)
    • 플러터 (17)
    • 안드로이드 스튜디오 (1)
    • 윈도우즈 (1)
    • 잡다한 백엔드 지식 (1)
    • 디자인 패턴 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 이펙티브 자바
  • Java
  • pnpm
  • 이펙티브자바
  • 자바스크립트
  • 서버리스 컴퓨팅
  • item8
  • 작업기억공간
  • NEXT JS
  • 자바스크립트 면접
  • 러스트
  • Javadoc 자바독 자바주석 주석 Comment
  • item9
  • item7
  • 참조 해제
  • 토비의 스프링
  • 느린 쿼리
  • 싱글톤 패턴
  • 외래키 제약조건
  • 빈 검증
  • Pre-rendering
  • 프로그래머의 뇌
  • 플라이웨이트패턴
  • 디자인패턴
  • 자바 검증
  • 추상 팩터리 패턴
  • 싱글턴
  • 이펙티브 자바 item9
  • 메이븐 골
  • serverless computing
  • 자바
  • 객체복사
  • 슬로우 쿼리
  • Next.js
  • 도커공식문서
  • 팩터리 메서드 패턴
  • rust
  • 메이븐 라이프사이클
  • bean Validation
  • 메이븐 페이즈
  • prerendering
  • 자바스크립트 인터뷰
  • 싱글톤
  • next js app
  • 알고리즘
  • 스프링 검증
  • try-with-resources
  • MSSQL
  • 자바 디자인패턴
  • 자료구조

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Jake Seo

제이크서 위키 블로그

프레임워크/스프링 프레임워크

Spring Boot Configuration Processor 란?

2023. 8. 2. 09:36

Spring Boot Configuration Processor 란?

  • Configuration 메타데이터를 처리하는데 도움을 주기 위한 도구이다.
  • 프로퍼티의 속성을 수동으로 추적하기 까다롭고 오류가 발생하기 쉬운 대규모 프로젝트에 용이하다.
  • 메타데이터 생성을 자동화함으로써 더 나은 코딩 관행을 장려하고 개발자 생산성을 향상시킨다.

사용하는 이유

  • 우리는 보통 프로퍼티의 값을 설정할 때, 어떤 기능을 하는지, 기본 값이 있는지, 더이상 사용되지 않는지, 속성이 존재하는지조차 모르는 경우가 많다.
  • Spring Boot Configuration Processor 를 통해 이러한 불편함을 해결할 수 있다.

IDE 의 자동 완성 (Auto-Completion in IDEs)

  • IDE 는 메타데이터를 제공받음으로써, 개발자에게 자동 완성 및 유효성 검사 기능을 제공할 수 있다.
  • 구성정보 옵션이 설명, 유형 및 기본 값과 함께 IDE 에 표기되므로 개발자가 애플리케이션의 구성 옵션을 훨씬 쉽게 이해하고 사용 가능하다.

문서 생성 (Documentation Generation)

  • 구성정보 프로퍼티에 대한 문서를 생성할 수 있다.
  • 속성, 설명, 기본 값 등이 자동으로 문서화되어 코드의 유지보수 및 투명성을 높일 수 있다.

유효성 검사 및 타입 변환 (Validation and Type Conversion)

  • 유효성 검사 규칙을 적용하고 사용자 지정 구성 유형에 대한 유형 변환을 처리할 수 있다.

사용 방법

의존성 추가

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

Configuration Properties 정의

  • @ConfigurationProperties 애노테이션을 꼭 사용해주어야 한다.
  • configuration processor 는 이 애노테이션이 붙은 클래스 및 메서드를 검색하여 configuration 메타데이터를 생성한다.
@Configuration
@ConfigurationProperties(prefix = "database")
public class DatabaseProperties {

    public static class Server {

        private String ip;
        private int port;

        // standard getters and setters
    }

    private String username;
    private String password;
    private Server server;

    // standard getters and setters
}
database.username=username
database.password=password

테스트

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnnotationProcessorApplication.class)
@TestPropertySource("classpath:databaseproperties-test.properties")
public class DatabasePropertiesIntegrationTest {

    @Autowired
    private DatabaseProperties databaseProperties;

    @Test
    public void whenSimplePropertyQueriedThenReturnsPropertyValue()
      throws Exception {
        Assert.assertEquals("Incorrectly bound Username property",
          "username", databaseProperties.getUsername());
        Assert.assertEquals("Incorrectly bound Password property",
          "password", databaseProperties.getPassword());
    }
}

프로젝트 컴파일 후 메타데이터 결과 보기

  • 프로젝트를 빌드하면, 프로세서가 json 파일을 생성한다.
  • target/classes/META-INF/spring-configuration-metadata.json 경로에 해당 파일이 생긴다.
{
  "groups": [
    {
      "name": "database",
      "type": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties"
    },
    {
      "name": "database.server",
      "type": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties$Server",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties",
      "sourceMethod": "getServer()"
    }
  ],
  "properties": [
    {
      "name": "database.password",
      "type": "java.lang.String",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties"
    },
    {
      "name": "database.server.ip",
      "type": "java.lang.String",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties$Server"
    },
    {
      "name": "database.server.port",
      "type": "java.lang.Integer",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties$Server",
      "defaultValue": 0
    },
    {
      "name": "database.username",
      "type": "java.lang.String",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties"
    }
  ],
  "hints": []
}

(옵셔널) 이외 메타데이터 추가하기

  • JavaDoc 커멘트를 추가하고, 기본 값, 최소 값, 최대 값 등을 설정할 수 있다.
public static class Server {

    /**
     * The IP of the database server
     */
    private String ip;

    /**
     * The Port of the database server.
     * The Default value is 443.
     * The allowed values are in the range 400-4000.
     */
    @Min(400)
    @Max(800)
    private int port = 443;

    // standard getters and setters
}
{
  "groups": [
    {
      "name": "database",
      "type": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties"
    },
    {
      "name": "database.server",
      "type": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties$Server",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties",
      "sourceMethod": "getServer()"
    }
  ],
  "properties": [
    {
      "name": "database.password",
      "type": "java.lang.String",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties"
    },
    {
      "name": "database.server.ip",
      "type": "java.lang.String",
      "description": "The IP of the database server",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties$Server"
    },
    {
      "name": "database.server.port",
      "type": "java.lang.Integer",
      "description": "The Port of the database server. The Default value is 443.
        The allowed values are in the range 400-4000",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties$Server",
      "defaultValue": 443
    },
    {
      "name": "database.username",
      "type": "java.lang.String",
      "sourceType": "com.example.autoconfiguration.annotationprocessor.DatabaseProperties"
    }
  ],
  "hints": []
}

힌트는 지금은 사용되지 않았지만, 사용할 수 있는 값의 집합 등으로 사용자가 어떤 값을 사용할지에 대한 힌트를 제공할 수 있다.

IDE 사용하기

  • 일단 셋업이 된 이후에는 개발자는 자동완성, 검증, 문서화 기능 등의 혜택을 볼 수 있다.

레퍼런스

  • https://www.baeldung.com/spring-boot-configuration-metadata
반응형
저작자표시 비영리 (새창열림)

'프레임워크 > 스프링 프레임워크' 카테고리의 다른 글

@TestConfiguration 애노테이션이란?  (0) 2023.08.03
@DataJpaTest 애노테이션이란?  (0) 2023.08.03
@EnableGlobalMethodSecurity 애노테이션이란?  (0) 2023.07.31
@EnableWebSecurity 애노테이션이란?  (0) 2023.07.31
@EnableWebMvc 애노테이션이란?  (0) 2023.07.31
    '프레임워크/스프링 프레임워크' 카테고리의 다른 글
    • @TestConfiguration 애노테이션이란?
    • @DataJpaTest 애노테이션이란?
    • @EnableGlobalMethodSecurity 애노테이션이란?
    • @EnableWebSecurity 애노테이션이란?
    Jake Seo
    Jake Seo
    ✔ 잘 보셨다면 광고 한번 클릭해주시면 큰 힘이 됩니다. ✔ 댓글로 틀린 부분을 지적해주시면 기분 나빠하지 않고 수정합니다. ✔ 많은 퇴고를 거친 글이 좋은 글이 된다고 생각합니다. ✔ 간결하고 명료하게 사람들을 이해 시키는 것을 목표로 합니다.

    티스토리툴바