반응형

기본

설명

  • 스프링에서는 @ConfigurationProperties을 활용하여 application.properties에 정의한 값들을 객체로 만들어 사용할 수 있게 해준다.
  • 아래는 그 기본 예제를 설명한다.

application.properties

card-info.description=Card Info Properties Test

card-info.card-list[0].name=BlackCard
card-info.card-list[0].color=black
card-info.card-list[1].name=WhiteCard
card-info.card-list[1].color=white

card-info.card-map.BLACK.name=BlackCard
card-info.card-map.BLACK.color=black
card-info.card-map.WHITE.name=WhiteCard
card-info.card-map.WHITE.color=white

CardType

public enum CardType {
    BLACK,
    WHITE
}

Card

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Card {
    private String name;
    private String color;
}

CardInfoProperties

@Data
@Component
@ConfigurationProperties(prefix = "card-info")
public class CardInfoProperties {
    private String description;
    private List<Card> cardList;
    private Map<CardType, Card> cardMap;
}
  • 아래처럼 설정시 Properties 클래스 상단에 @Component를 선언하지 않아도 애플리케이션 내에 @ConfigurationProperties 선언된 클래스를 모두 찾아 빈 등록을 해준다. (@Component로 Properties 객체를 빈으로 등록해서 사용한다면 아래 설정 필요 X)
@EnableConfigurationProperties
@ConfigurationPropertiesScan
public class Application { ... }

CardInfoPropertiesTest

@SpringBootTest
public class CardInfoPropertiesTest {
    @Autowired
    private CardInfoProperties cardInfoProperties;

    @Test
    public void testCardInfoProperties() {
        String description = "Card Info Properties Test";

        List<Card> cardList = List.of(
            new Card("BlackCard", "black"),
            new Card("WhiteCard", "white")
        );

        Map<CardType, Card> cardMap = Map.of(
            CardType.BLACK, new Card("BlackCard", "black"),
            CardType.WHITE, new Card("WhiteCard", "white")
        );

        assertEquals(description, cardInfoProperties.getDescription());
        assertEquals(cardList, cardInfoProperties.getCardList());
        assertEquals(cardMap, cardInfoProperties.getCardMap());
    }
}

yml 파일 나눠서 관리하기

설명

~/src/main/resources/card-info

common.yml
card-info:
  description: Card Info Properties Test
black.yml
card-info:
  card-list[0]:
    name: BlackCard
    color: black
  card-map.BLACK:
    name: BlackCard
    color: black
white.yml
card-info:
  card-list[1]:
    name: WhiteCard
    color: white
  card-map.WHITE:
    name: WhiteCard
    color: white

CardInfoProperties

@Data
@Component
@ConfigurationProperties(prefix = "card-info")
@PropertySource(value = "classpath:card-info/*.yml", factory = YamlPropertySourceFactory.class) // 추가
public class CardInfoProperties {
    private String description;
    private List<Card> cardList;
    private Map<CardType, Card> cardMap;
}
반응형

'Development > Spring' 카테고리의 다른 글

[Spring] Scheduler Lock  (0) 2021.11.25
[Spring] Replication  (0) 2021.11.15
[Spring] @Value  (0) 2021.08.02
[Spring] Sharding  (0) 2021.07.07
[Spring] Thymeleaf  (0) 2021.06.26

+ Recent posts