[Day 27 | Spring] Spring Boot 개념 및 코드 설명

y♡ding·2024년 11월 19일

데브코스 TIL - Spring

목록 보기
13/46

1. Spring Boot 시작

Spring Boot는 애플리케이션의 설정 및 실행을 단순화합니다. 이를 위해 제공되는 핵심 요소는 다음과 같습니다:

1.1 @SpringBootApplication

  • Spring Boot에서 애플리케이션의 시작 클래스를 지정하는 어노테이션입니다.
  • 내부적으로 @Configuration, @EnableAutoConfiguration, @ComponentScan을 포함하고 있습니다.
  • 해당 어노테이션이 위치한 패키지와 그 하위 패키지를 스캔하여 빈을 자동 등록합니다.

1.2 SpringApplication

  • Spring Boot 애플리케이션의 진입점.
  • 애플리케이션 실행(run 메서드 호출)과 환경설정 관리 등을 수행합니다.

2. 환경 설정

Spring Boot는 환경 설정 파일을 통해 다양한 설정값을 관리합니다.

2.1 application.propertiesapplication.yml

  • 두 파일 모두 애플리케이션의 설정값을 키-값(key=value) 구조로 지정합니다.
  • application.yml은 YAML 포맷으로, 중첩된 설정을 더 읽기 쉽게 표현할 수 있습니다.

2.2 @PropertySource@ConfigurationProperties

  • @PropertySource: 외부 설정 파일을 읽어오는 데 사용합니다.
  • @ConfigurationProperties: 설정 파일의 값을 특정 POJO에 바인딩합니다.
@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {
    @Value("${app.name}")
    private String appName;

    // getter, setter...
}

3. 로깅 (Logging)

Logging :: Spring Boot
Spring Boot는 로깅 프레임워크를 통합하여 애플리케이션의 로그를 관리합니다.

3.1 기본 로깅 프레임워크

  • 기본적으로 Logback을 사용하며, log4j2 등 다른 로깅 프레임워크로 쉽게 교체 가능.
  • 로깅 설정은 logback.xml 또는 logback-spring.xml에서 관리.

3.2 로그 출력 형태

  • 로그의 기본 출력에는 다음 요소가 포함됩니다:
    • 애플리케이션 이름 (spring.application.name 설정 시 출력됨)
    • 스레드 이름 (대괄호로 표시)
    • Logger 이름 (일반적으로 클래스 이름)
    • 로그 메시지
  • 로그 형태는 XML 설정 파일을 통해 사용자 정의 가능.

4. Profiles

Profiles는 애플리케이션의 환경별 설정을 관리하는 방법입니다.

  • 예: 개발(dev), 테스트(test), 운영(prod) 환경에 따라 다른 설정 적용 가능.
  • 활성화 방법:
    spring.profiles.active=dev
  • 환경별 설정은 application-{profile}.properties 또는 application-{profile}.yml로 분리하여 관리.

5. 패키지 구조

Structuring Your Code :: Spring Boot
Spring Boot에서는 권장되는 패키지 구조를 따르는 것이 좋습니다.

권장 구조

  • 계층화된 구조로, 컨트롤러, 서비스, 리포지토리 등을 역할에 따라 분리.
  • @ComponentScan에 의해 기본적으로 @SpringBootApplication의 패키지와 하위 패키지에서 빈을 검색합니다.
com
 +- example
     +- myapplication
         +- MyApplication.java        // 메인 애플리케이션
         +- customer
             +- Customer.java          // 도메인 모델
             +- CustomerController.java // 컨트롤러
             +- CustomerService.java   // 서비스
             +- CustomerRepository.java // 리포지토리

병렬 구조 시 문제와 해결

  • 병렬 구조로 패키지를 구성할 경우 자동 스캔되지 않을 수 있습니다.
  • 해결: @Import를 사용해 다른 패키지의 설정을 명시적으로 가져옵니다.
@Configuration
public class BeanConfig {
    @Bean
    public DatabaseService service() {
        return new DatabaseService();
    }
}

@SpringBootApplication
@Import(BeanConfig.class) // BeanConfig 등록
public class BootApplication implements CommandLineRunner {

    @Autowired
    private ApplicationContext ctx;

    @Override
    public void run(String... args) throws Exception {
        DatabaseService service = ctx.getBean("service", DatabaseService.class);
        List<String> lists = service.getList();
        System.out.println(lists); // 출력
    }
}

코드 설명

1. DatabaseService

  • 데이터베이스 관련 비즈니스 로직 제공.
public class DatabaseService {
    public List<String> getList() {
        return Arrays.asList("홍길동", "박문수");
    }
}

2. BeanConfig

  • DatabaseService를 빈으로 등록.
@Configuration
public class BeanConfig {
    @Bean
    public DatabaseService service() {
        return new DatabaseService();
    }
}

3. BootApplication

  • 메인 애플리케이션 클래스.
  • @ImportBeanConfig를 가져와 빈을 활용.
@SpringBootApplication
@Import(BeanConfig.class)
public class BootApplication implements CommandLineRunner {

    @Autowired
    private ApplicationContext ctx;

    @Override
    public void run(String... args) throws Exception {
        DatabaseService service = ctx.getBean("service", DatabaseService.class);
        List<String> lists = service.getList();
        System.out.println(lists);
    }
}

정리

  1. Spring Boot는 애플리케이션 구성을 단순화하는 프레임워크로, 자동 설정과 강력한 프로파일 관리 기능을 제공합니다.
  2. 패키지 구조를 권장대로 따르고, 병렬 구조일 경우 @Import를 활용해 빈 등록 문제를 해결할 수 있습니다.
  3. 로깅, 환경 설정, 프로파일 관리 등을 통해 개발 및 운영 환경에서 유연하게 애플리케이션을 관리할 수 있습니다.

0개의 댓글