스프링 부트 2.6.5 버전을 기준으로 작성됨
H2 데이터베이스 Version 2.2.224 (2023-09-17)
데이터 접근 기술
SQLMapper
ORM 관련 기술
Repository 는 향후 다양한 데이터 접근 기술 구현체로 손쉽게 변경하기 위해 인터페이스 도입
public interface ItemRepository {
Item save(Item item);
void update(Long itemId, ItemUpdateDto updateParam);
Optional<Item> findById(Long id);
List<Item> findAll(ItemSearchCond cond);
}
검색과 수정은 Dto 클래스를 각각 만들어서 처리
ItemSearchCond
ItemUpdateDto
// Dto 사용
@Override
public void update(Long itemId, ItemUpdateDto updateParam) {
Item findItem = findById(itemId).orElseThrow();
findItem.setItemName(updateParam.getItemName());
//...
}
@EventListener(ApplicationReadyEvent.class)
public void initData() {
itemRepository.save(new Item("itemA", 10000, 10));
// 추가할 데이터넣기
}
@EventListener(ApplicationReadyEvent.class
: 스프링 컨테이너가 완전히 초기화를 다 끝내고, 실행 준비가 되었을 때 발생하는 이벤트 initData()
메서드를 호출해준다.@PostConstruct
를 사용할 경우 AOP 같은 부분이 아직 다 처리되지 않은 시점에 호출될 수 있기에 간혹 문제 발생가능성이 있다. ex) @Transactional
과 관련된 AOP가 적용되지 않은 상태로 호출@EventListener(ApplicationReadyEvent.class)
는 AOP를 포함한 스프링 컨테이너가 완전히 초기화 된 이후에 호출되기 때문에 이런 문제가 발생하지 않는다. @Import(MemoryConfig.class)
@SpringBootApplication(scanBasePackages = "hello.itemservice.web")
public class ItemServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ItemServiceApplication.class, args);
}
@Bean
@Profile("local")
public TestDataInit testDataInit(ItemRepository itemRepository) {
return new TestDataInit(itemRepository);
}
}
@Import
: 설정파일로 MemoryConfig 클래스를 사용@scanBasePackages
: 컴포넌트 스캔 경로를 hello.itemservice.web
하위로 지정@Profile
: 특정 프로필의 경우에만 해당 스프링 빈을 등록 testDataInit
이라는 스프링 빈을 등록스프링은 로딩 시점에 application.properties
의 spring.profiles.active
속성을 읽어서 프로필을 사용
이 프로필은 로컬 (내 PC), 운영환경, 테스트 실행 등 다양한 환경에 따라 다른 설정을 할 때 사용하는 정보
프로필을 사용함으로써 현재 환경에 따른 설정을 할 수 있다!
/src/main/resource
하위의 application.properties
spring.properties.active=local
application.properties
는 /src/main
하위의 자바 객체를 실행할 때 (주로 main() ) 동작하는 스프링 설정/src/test/resources
하위의 application.properties
spring.profiles.active=test
application.properties
는 /src/test
하위의 자바 객체를 실행할 때 동작하는 스프링 설정null
값은 허용 x이메일, 전화번호 등은 언제든 바뀔 수 있고 주민등록번호는 3가지 조건이 다 만족해보이는 것처럼 보이지만 현실과 비지니스 규칙은 생각보다 쉽게 변하며 주민등록 조차도 여러가지 이유로 변경될 수 있다.
비지니스 환경은 언젠가 변한다.
🔖 학습내용 출처