2022-04-07 TIL
26907 ワード
18日目プログラマーバックエンド死亡ルート
チーム面談
-開発を面白くする.
-来週からオフラインコードのコメント
SpringBoot part1
PropertySource
package org.springframework.core.env;
public interface EnvironmentCapable {
Environment getEnvironment();
}
version = v1.0.0
kdt.version = v1.0.0
kdt.support-vendors = a, b, c, d, e, f, g
kdt.minimun-order-amount = 1
var applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class);
// 환경설정 property 값을 가져 올 수 있다.
var environment = applicationContext.getEnvironment();
var version = environment.getProperty("kdt.version");
var vendors = environment.getProperty("kdt.support-vendors", List.class);
var minimumOrderAmount = environment.getProperty("kdt.minimun-order-amount", Integer.class);
// 만약 찾는 property가 없다면 기본값 지정도 가능
@Value("${kdt.version:v.0.0.0}")
private String version;
@Value("${kdt.minimum-order-amount:0}")
private int minimumOrderAmount;
@Value("${kdt.support-vendors:a, b, c, d, e, f, g}")
private List<String> supportVendors;
// System에 설정된 값도 불러 올 수 있다.
@Value("${JAVA_HOME}")
private String javaHome;
// 생성자의 매개변수에도 가능
public constructor(@Value("${version:v0.0.0}") String version) { ... }
// @Value 없이도 properties를 찾을 수 있게 해줌
@Configuration
@ConfigurationProperties(prefix = "kdt")
public class OrderProperties {
private String version;
private int minimumOrderAmount;
private List<String> supportVendors;
private String description;
// 예외는 있음
@Value("${JAVA_HOME}")
private String javaHome;
...
}
// SpringBoot에서 사용하는 기능이라 @EnableConfigurationProperties을 붙여야 함
@Configuration
@PropertySource(value = "...", factory = ...)
@ComponentScan(basePackages = {"...", "...", "..."})
@EnableConfigurationProperties
public class AppConfiguration { ... }
ソース:docs。spring.io
YAML
// springframework의 @propertySource는 yaml을 기본적으로 지원하지 않기 때문에
// 따로 factory를 만들어서 사용해야 한다.
@PropertySource(value = "application.yaml", factory = YamlPropertiesFactory.class)
public class AppConfiguration { ... }
// yaml을 가져오기 위한 factory 코드
public class YamlPropertiesFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
var yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
yamlPropertiesFactoryBean.setResources(encodedResource.getResource());
var properties = yamlPropertiesFactoryBean.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
Profile
// Qualifier 대신 Profile을 사용 할 수 있다.
@Profile({"local", "default"})
public class ... { ... }
@Profile("dev")
public class ... { ... }
// applicationContext의 environment에서 profile을 지정 할 수 있다.
// profile을 지정한 후에는 새로고침을 해줘야 한다.
public class ... {
var applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(AppConfiguration.class);
var environment = applicationContext.getEnvironment();
environment.setActiveProfiles("dev");
applicationContext.refresh();
}
// @Bean @Configuration에도 @Profile을 사용 할 수 있다.
// 어플리케이션 시작 단계에서 프로파일을 지정 할 수 있다.
@SpringBootApplication
@ComponentScan(basePackages = {"...", "...", "..."})
public class Application {
public static void main(String[] args) {
var springApplication = new SpringApplication(KdtApplication.class);
springApplication.setAdditionalProfiles("local");
var applicationContext = springApplication.run(args);
}
}
次はyamlファイルコードです.kdt:
version: "default-v1.0.0"
minimum-order-amount: 1
support-vendors:
- default
description: |-
line 1 hello world
line 2 xxxx
line 3
---
spring.config.activate.on-profile: :local
kdt:
version: "v1.0.0"
minimum-order-amount: 1
support-vendors:
- a
- b
- c
- d
description: |-
line 1 hello world
line 2 xxxx
line 3
---
spring.config.activate.on-profile: :dev
kdt:
version: "v1.0.0-dev"
minimum-order-amount: 1
support-vendors:
- dev-a
- dev-b
description: |-
dev
dev
Resource
var resource = applicationContext.getResource("application.yaml");
var resource2 = applicationContext.getResource("file:sample.txt");
System.out.println("resource = " + resource.getClass().getCanonicalName());
var file = resource.getFile();
var strings = Files.readAllLines(file.toPath());
System.out.println(strings.stream().reduce("", (a, b) -> a + "\n" + b));
var resource3 = applicationContext.getResource("https://stackoverflow.com/");
var readableByteChannel = Channels.newChannel(resource3.getURL().openStream());
var bufferedReader = new BufferedReader(Channels.newReader(readableByteChannel, StandardCharsets.UTF_8));
var contents = bufferedReader.lines().collect(Collectors.joining("\n"));
System.out.println("contents = " + contents);
妙技
Reference
この問題について(2022-04-07 TIL), 我々は、より多くの情報をここで見つけました https://velog.io/@nnagman/2022-04-07-TILテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol