사용자 도구

사이트 도구


springframework:springboot:properties

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
springframework:springboot:properties [2018/08/28 09:27]
kwon37xi [profile include]
springframework:springboot:properties [2024/03/04 16:27] (현재)
kwon37xi
줄 1: 줄 1:
 ====== SpringBoot Properties ====== ====== SpringBoot Properties ======
   * [[springframework:springboot|SpringBoot]] 에서 설정 값 외재화   * [[springframework:springboot|SpringBoot]] 에서 설정 값 외재화
 +  * [[springframework:springboot:properties_migrator|spring-boot-properties-migrator]]
   * 보통 ''yml''을 이용해서 ''application.yml''로 지정한다.   * 보통 ''yml''을 이용해서 ''application.yml''로 지정한다.
 +  * ''YamlPropertiesFactoryBean''
 +  * ''PropertiesFactoryBean''
 +  * ''YamlPropertySourceLoader''
 +  * ''PropertiesPropertySourceLoader''
 +
 +===== 기본값 설정 =====
 +  * 이미 지정된 property 이면, 해당 값을 사용하고, 그게 아니면 기본값을 사용하는 구조로
 +  * ''EXTERNAL_USERNAME/EXTERNAL_PASSWORD'' 환경 변수 혹은 ''external.username/external.password'' 프라퍼티가 존재하면 그 값을 사용하고 그게 아니면 '':'' 뒤에 지정된 값을 사용한다.
 +<code yml>
 +testing:
 +  my:
 +    username: ${external.username:system}
 +    password: ${external.password:test}
 +</code>
 +  * [[https://stackoverflow.com/a/49644607/1051402|SpEL로 기본값 지정]]. SpEL은 ''@Value''로 값을 읽는 경우에만 지정 가능하며, ''@ConfigurationProperties''를 사용할 때는 안 된다. 혼란스럽기 때문에 안 사용하는게 나을듯 하다.
 +
 +<code yml>
 +testing:
 +  my:
 +    username: ${external.username:user}
 +    password: ${external.password:#{' test'}}
 +</code>
 +<code java>
 +@Value("${testing.my.username}")
 +private String username;
 +
 +@Value("${testing.my.password}")
 +private String password;
 +</code>
  
 ===== profile 별 설정 ===== ===== profile 별 설정 =====
줄 32: 줄 62:
 ===== profile include ===== ===== profile include =====
   * 프로필을 자동 활성화 한다.    * 프로필을 자동 활성화 한다. 
 +  * Spring Boot 2.3 이전에서 사용하는 방식.
 +  * 2.4 부터는 [[https://github.com/kwon37xi/research-spring-boot-2.4/tree/master/profile-group|spring.config.import 와 profile group 기능 사용]]
   * ''application.yml''<code>   * ''application.yml''<code>
 spring.profiles: production spring.profiles: production
줄 91: 줄 123:
   * [[https://github.com/spring-projects/spring-framework/blob/master/spring-beans/src/main/java/org/springframework/beans/factory/config/YamlPropertiesFactoryBean.java|YamlPropertiesFactoryBean]] 를 사용하여 yaml을 ''Property'' 객체로 적재할 수 있다. ''PropertySource''로 등록되는 것은 아니므로 헷갈리면 안된다.   * [[https://github.com/spring-projects/spring-framework/blob/master/spring-beans/src/main/java/org/springframework/beans/factory/config/YamlPropertiesFactoryBean.java|YamlPropertiesFactoryBean]] 를 사용하여 yaml을 ''Property'' 객체로 적재할 수 있다. ''PropertySource''로 등록되는 것은 아니므로 헷갈리면 안된다.
   * 이 경우 ''@Value("#propertyObjectName['key']")'' 형태로 사용가능해 진다.   * 이 경우 ''@Value("#propertyObjectName['key']")'' 형태로 사용가능해 진다.
 +
 +===== YAML을 ''@PropertySource''로 사용하기 =====
 +  * [[https://github.com/spring-projects/spring-framework/blob/master/spring-beans/src/main/java/org/springframework/beans/factory/config/YamlPropertiesFactoryBean.java|YamlPropertiesFactoryBean]] 로 명시적으로 지정해줄 수 있다.
 +  * [[https://www.baeldung.com/spring-yaml-propertysource|@PropertySource with YAML Files in Spring Boot | Baeldung]]
 +
 +<code java>
 +@PropertySource(
 +    value = "classpath:foo.yml", 
 +    factory = YamlPropertySourceFactory.class
 +)
 +</code>
 +
 +<code java>
 +public class YamlPropertySourceFactory implements PropertySourceFactory {
 +
 +    @Override
 +    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) 
 +      throws IOException {
 +        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
 +        factory.setResources(encodedResource.getResource());
 +
 +        Properties properties = factory.getObject();
 +
 +        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
 +    }
 +}
 +
 +</code>
 ===== @ConfigurationProperties ===== ===== @ConfigurationProperties =====
   * ''@EnableConfigurationProperties'' 가 설정돼 있어야 한다.   * ''@EnableConfigurationProperties'' 가 설정돼 있어야 한다.
   * [[http://www.baeldung.com/configuration-properties-in-spring-boot|Guide to @ConfigurationProperties in Spring Boot | Baeldung]]   * [[http://www.baeldung.com/configuration-properties-in-spring-boot|Guide to @ConfigurationProperties in Spring Boot | Baeldung]]
   * [[http://javacan.tistory.com/entry/springboot-configuration-properties-class|자바캔(Java Can Do IT) :: 스프링 부트 커스텀 설정 프로퍼티 클래스 사용하기]]   * [[http://javacan.tistory.com/entry/springboot-configuration-properties-class|자바캔(Java Can Do IT) :: 스프링 부트 커스텀 설정 프로퍼티 클래스 사용하기]]
 +  * 아래 의존성을 추가하면 yml IDE 자동 완성이 지원되는 듯<code>
 +compile "org.springframework.boot:spring-boot-configuration-processor"
 +</code>
 +  * ''@ConfigurationProperties'' 애노테이션이 붙은 클래스에 직접 ''@Configuration''을 붙여서 생성하거나, 별도로 ''@Bean''으로 생성하면 자동으로 값이 차서 Bean 으로 생성된다.
 +  * ''javax.validation'' 애노테이션을 걸어주면 자동 validation이 작동한다.
 +===== PropertySource과 properties 로그로 남기기 =====
 +  * [[https://stackoverflow.com/questions/44115216/spring-boot-when-application-properties-and-application-yml-are-loaded-by-a-spr|Spring Boot: When application.properties and application.yml are loaded by a spring boot application - Stack Overflow]]
  
 +<code java>
 +@Component
 +public class LoadedConfigFileListener implements ApplicationListener<ApplicationReadyEvent>, Ordered {
 +
 +    @Override
 +    public void onApplicationEvent(ApplicationReadyEvent event) {
 +        MutablePropertySources propertySources = event.getApplicationContext().getEnvironment().getPropertySources();
 +        Iterator<PropertySource<?>> propertySourceIterator = propertySources.iterator();
 +        propertySourceIterator.forEachRemaining(propertySource -> log.info("Successfully loaded: \"{}\" ({}) into application context", propertySource.getName(), propertySource.getSource()));
 +    }
 +
 +    @Override
 +    public int getOrder() {
 +        return ConfigFileApplicationListener.DEFAULT_ORDER + 1;
 +    }
 +}
 +
 +</code>
  
 ===== 모든 properties 로그로 남기기 ===== ===== 모든 properties 로그로 남기기 =====
   * [[https://gist.github.com/sandor-nemeth/f6d2899b714e017266cb9cce66bc719d|PropertyLogger.java]]   * [[https://gist.github.com/sandor-nemeth/f6d2899b714e017266cb9cce66bc719d|PropertyLogger.java]]
-  * 아래와 같이 ''ContextRefreshEvent'' 를 받는 ''@EventListener'' Bean을 등록해주고, 거기서 로깅하면 된다.+  * 최종적으로 결정된 properties 목록을 확인하고자 할 때, 아래와 같이 ''ContextRefreshEvent'' 를 받는 ''@EventListener'' Bean을 등록해주고, 거기서 로깅하면 된다.
 <code java> <code java>
 @Component @Component
줄 123: 줄 208:
 } }
 </code> </code>
 +
 +===== addional property 파일지정 =====
 +  * 기존 프라퍼티 파일들보다 우선순위가 높게 추가 프라퍼티 파일을 지정할 수 있다. **추가**되는 것이므로 기존 값도 계속 함께 읽는다.
 +<code>
 +spring.config.additional-location=classpath:/custom-config,file:./custom-config
 +</code>
 +
 +===== JSON을 통한 Override =====
 +  * JSON 으로 명령행에서 properties를 override할 수 있다. JSON 으로 여러 프라퍼티를 지정할 수 있다.
 +  * 시스템 프라퍼티로 : ''spring.application.json={"keyname":"value"}''
 +  * 환경 변수로 : ''SPRING_APPLICATION_JSON={"keyname":"value"}''
 +
 +
 +===== EnvironmentPostProcessor 를 통한 프라퍼티 값 후처리 =====
 +  * [[https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/env/EnvironmentPostProcessor.html|EnvironmentPostProcessor]] 를 사용하면 읽어들인 프라퍼티 값에 대한 후처리를 할 수 있다.
 +  * 예를들면, 프라퍼티 값을 암호화 해서 저장해 두고, 실제 읽을 때는 복호화해서 읽는 등의 작업이 가능하다.
 +  * [[https://www.baeldung.com/spring-boot-environmentpostprocessor|EnvironmentPostProcessor in Spring Boot | Baeldung]]
 +  * [[https://javacan.tistory.com/entry/activate-some-profile-when-no-active-profiles-in-boot|자바캔(Java Can Do IT) :: 스프링 부트에서 EnvironmentPostProcessor로 기본 프로필 설정하기]]
 +  * [[https://wedul.site/458|Spring Boot application.properties 암호화 내역 복호화 방법]]
 +  * 작성한 코드를 ''META-INF/spring.factories'' 에 등록해야 한다.<code>
 +org.springframework.boot.env.EnvironmentPostProcessor=
 +  com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor
 +</code>
 +
 +===== YAML Duration =====
 +  * Spring Boot 2.1 부터 [[https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html|Duration]] 을 지정할 수 있다.
 +  * ''100ms'' 형태로 시간 단위를 문자로 지정하면 된다.
 +  * ''ns'' for nanoseconds
 +  * ''us'' for microseconds
 +  * ''ms'' for milliseconds
 +  * ''s'' for seconds
 +  * ''m'' for minutes
 +  * ''h'' for hours
 +  * ''d'' for days
  
 ===== 참고 ===== ===== 참고 =====
springframework/springboot/properties.1535416066.txt.gz · 마지막으로 수정됨: 2018/08/28 09:27 저자 kwon37xi