java 코드에서 configuration 파일에서 @PropertySource
에 파일 등록 후 사용
var environment = appContext.getEnvironment();
var version = environment.getProperty("kdt.version");
@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-> 환경변수값 반환
환경변수가 가장 우선순위 높음
kdt:
version: "v1.0"
minimum-order-amount: 1
support-vendors: // 배열
- a // - 이거 다음에 한 칸 띄어야 함
- b
- c
- d
description: |- // - 이거 의미는 마지막 개행문자 제거
// | 이걸로 여러 줄 문자 입력
line 1 hello world
line 2 xxx
line 3
@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);
}
}
@ConfigurationProperties(prefix = “속성”)
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());
Resource
, ResourceLoader
인터페이스로 API 제공