SpringFramework/Spring 22

동적 빈 생성

Spring에서 제공하는 ConfigurableListableBeanFactory 클래스를 이용하여 동적으로 빈 등록이 가능하다. 동적 생성할 클래스 선언 public class DynamicClass { // 빈 등록시 생성자 호출여부 확인용 public DynamicClass() { System.out.println("생성자 호출!"); } public void func(){ System.out.println("Test"); } } 테스트 코드를 통한 동적 빈 생성 및 조회 @SpringBootTest public class DynamicClassTest { @Test void test(){ StaticApplicationContext staticApplicationContext = new Stati..

추상클래스를 사용한 통합 배치 관리 프로그램

배치 병렬 처리를 위한 쓰레드 빈 생성 클래스 @Configuration @EnableAsync public class ThreadConfig { @Bean(name="jobExecutor") public Executor jobExecutor(){ ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.setQueueCapacity(30); taskExecutor.setThreadNamePrefix("jobThead-"); taskExecutor.initialize(); return taskExecu..

String 중괄호 매핑 함수 (log.info 대신 사용)

log.info() 함수와 동일한 방식으로 String 문자를 합치는 함수를 구현 사용법 String str = makeStr("{} is test {}", 1234, "abcd"); private String makeStr(String text, Object ...args){ if(StringUtils.isEmpty(text)){ return ""; } // 중괄호 쌍이 없는 경우 작업하지 않음 if(!text.contains("{}")){ return text; } StringBuilder sb = new StringBuilder(); // 중괄호 쌍으로 문자열을 나눔 String[] split = text.split("\\{}"); for (int i = 0; i < split.length; i++..

SpringBoot CORS (WebMvcConfigurer 사용) 적용 방법

/* preflight Simple request가 아닌 요청 메시지보다 먼저 보내는 메시지로, 브라우저는 응답값으로 실제 데이터 전송 여부를 판단. CORS는 응답이 Access-Control-Allow-Credentials: true 을 가질 경우, Access-Controll-Allow-Origin의 값으로 *를 사용하지 못하게 막고 있다 Access-Control-Allow-Credentials: true를 사용하는 경우는 사용자 인증이 필요한 리소스 접근이 필요한 경우인데, 만약 Access-Control-Allow-Origin: *를 허용한다면, CSRF 공격에 매우 취약해져 악의적인 사용자가 인증이 필요한 리소스를 마음대로 접근할 수 있음. */ @Configuration public cla..

Spring Jsonp 관련 확인한 내용

요약 AbstractJsonpResponseBodyAdvice을 상속받아 사용하는 프로젝트는 Spring 버전을 2.0.x로 유지하거나, 버전업 이후 JSONP 응답을 직접 개발해야 레거시 시스템에서 Ajax jsopn 호출히 오류가 발생하지 않는다. (SpringBoot 2.1 부터는 JSONP 응답을 지원하지 않음, 라이브러리 또한 미지원) 내용 레거시 시스템 고도화 작업중 CORS 소스가 존재함을 확인 레거시 CORS 소스 @ControllerAdvice public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice { public JsonpAdvice() { super("callback"); } } 해당 소스를 리팩토링하여 아래 코드로 변경함...

MapStruct 설정 (ModelMapper 대안)

ModelMapper가 많이 사용하고 사용하기 편하나 성능 이슈가 있고, 아래 URL을 통해 확인할 수 있다. Performance of Java Mapping Frameworks | Baeldung MapStruct comes out on top, followed by JMapper as a close second. The other libraries follow far behind: Orika, ModelMapper, and Dozer. www.baeldung.com 따라서, 성능 이슈에 대응하기 위해 ModelMapper 대신 MapStruct를 대신 사용한다. MapStruct 설정 build.gradle 파일에 아래 의존성 추가 implementation 'org.mapstruct:mapstru..

AbstractJsonpResponseBodyAdvice Deprecated 대응

AbstractJsonpResponseBodyAdvice 를 상속받은 클래스를 제거하고, 아래 클래스를 추가한다. 신규 Cors origin 설정은 AbstractJsonpResponseBodyAdvice 클래스에서 선언한 대로 수정 작성한다. @Configuration public class WebConfig implements WebMvcConfigurer { // Spring Boot 버전업 대응으로 처리해두었음. JsonpAdvice 클래스 제거 후 사용 @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 사용 가능한 모든 URL에 대해 .allowedOrigins("*"); // 모..