SpringBoot #1.4 - Environment

텐저린티·2023년 6월 22일
0

데브코스

목록 보기
9/41
post-thumbnail

SpringBoot #1.4 - Environment

  • Environment profie
  • Profile
  • YAML로 property 작성
  • Resource

Environment

  • property + profile

Properties

  • 속성
  • 예를들어 개인정보같은 거는 외부 속성으로 만들어서 사용
  • JVM 정보나, OS 정보 같은 속성을 코드로 가져올 수 있도록 하는 인터페이스
  • 프로파일 파일로 만들어서 사용 가능 (resourse > .properties)
    • java 코드에서 configuration 파일에서 @PropertySource에 파일 등록 후 사용

      var environment = appContext.getEnvironment();
      var version = environment.getProperty("kdt.version");
  • java Property 클래스를 이용해서 properties를 주입 가능
    • @Component 스테레오타입을 이용해서 컴포넌트 스캔하도록 해야 주입됨.

    • value 타입이 맞지 않으면 Exception 발생

      @Component
      public class OrderProperties implements InitializingBean {
      
          @Value("v1.1.1")
      		// @Value("${kdt.version:v0.0.0}") -> if null get default value
          private String version;
      
      		@Value("${kdt.minimum-order-amount}")
          private Integer minimumOrderAmount;
      
          private List<String> supportVendors;
      
      		@Value("${JAVA_HOME}")
      		private String javaHome;
      
          @Override
          public void afterPropertiesSet() throws Exception {
              System.out.println("[OrderProperties] version -> " + version);
              System.out.println("[OrderProperties] minimumOrderAmount -> " + minimumOrderAmount);
              System.out.println("[OrderProperties] supportVendors -> " + supportVendors);
          }
      }
      // version -> v1.1.1
      // min~    -> .properties 파일에 기록한 프로퍼티
      // supportV-> null
      // javaHome-> 환경변수값 반환
    • 환경변수가 가장 우선순위 높음

YAML로 Property 작성

  • 마크언어 아님. 근데 가벼운 마크업 언어(XML, JSON 같은 데이터 직렬화)로 사용.
kdt:
  version: "v1.0"
  minimum-order-amount: 1
  support-vendors: // 배열
    - a // - 이거 다음에 한 칸 띄어야 함
    - b
    - c
    - d
  description: |- // - 이거 의미는 마지막 개행문자 제거
									// | 이걸로 여러 줄 문자 입력
    line 1 hello world
    line 2 xxx
    line 3
  • yaml 프로퍼티 적용법 1번
    • springboot에서는 yaml 파일을 인식하지 못하기 때문에
    • 이렇게 PropertySourceFactory를 상속해서 프로퍼티를 적용해줘야 한다.
@PropertySource(value = "application.yaml", factory = YamlPropertiesFactory.class)
public class AppConfiguration {
public class YamlPropertiesFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        var yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        yamlPropertiesFactoryBean.setResources(resource.getResource());

        var properties = yamlPropertiesFactoryBean.getObject();
        return new PropertiesPropertySource(resource.getResource().getFilename(), properties);
    }
}
  • YAML 적용법 2번
    • @ConfigurationProperties(prefix = “속성”)
    • 프로퍼티 클래스를 만들고 어노테이션 붙여서 사용하는 방식
      • YAML 파일 속성과 같은 이름의 필드 필요
      • 게터, 세터 필요
    • 스프링부트에서 외부 속성 이용해 별도 Bean 만드는 어노테이션
    • 특정 그룹 속성 모델링 가능 및 Bean 등록 가능
      • 대규모 플젝에서 유용
      • 배열 형식 속성 사용 가능
  • YAML 적용법 3번
    • 프로퍼티 클래스를 만드는 것은 2번과 동일
    • 필드에 @Value(”yaml속성이름”)으로 바인딩

Profile

  • 앱 설정 일부 분리 → 특정 환경에서만 사용 가능토록
  • 여러 Bean 정의가 특정 Profile 에서만 동작 가능
  • 특정 property를 profile로 정의 → profile 이 active일 때 적용 가능
var springApplication = new SpringApplication(SpringOrderApplication.class);
springApplication.setAdditionalProfiles("local");
var applicationContext = springApplication.run(args);

var orderProperties = applicationContext.getBean(OrderProperties.class);
System.out.println("version -> " + orderProperties.getVersion());
System.out.println("minimumOrderAmount -> " + orderProperties.getMinimumOrderAmount());
System.out.println("supportVendors -> " + orderProperties.getSupportVendors());
System.out.println("description -> " + orderProperties.getDescription());

리소스

  • 외부 리소스
    • 이미지, 텍스트, 암복호화 키 파일
  • Spring은 Resource, ResourceLoader 인터페이스로 API 제공
    • UrlResource
    • ClassPathResource
    • FileSystemResource
    • PathResource
    • ServletContextResource
    • InputStreamResource
    • ByteArrayResource
profile
개발하고 말테야

0개의 댓글

관련 채용 정보