[Lecture] (Inflean 김영한) 스프링 핵심원리 - 기본편

SAPCO·2022년 8월 21일
0

- [Lecture]

목록 보기
1/1

📍 0. 시작

강의를 들으면서 다시 리뷰하며 참고할 내용을 두서없이 적음.
강의와 정리에 투자하는 시간이 주객전도가 되지 않기위해 공유가 아닌 복습의 목적으로 흐름을 간단히 적는다.

📌 IntelliJ 단축키
자동완성 : cm + s + Enter
extract introduve variable : command option v
코드 내 오류난곳으로 이동 : f2
test생성 : cm + s + t
최근파일 : cm + e
extract method : cm + op + m
검색 : shift shift

📍 1. 객체지향 설계와 스프링

📍 2. 스프링 핵심원리 이해1 - 예제만들기

📌 11. 회원 도메인 설계

  • enum Grade
    enum기초
    실무에서 사용해보지 못했던건데 서치중 우아한형제 기술블로그에서 Enum에 대한 글을 보았다. 프로젝트에서 ERP에서 데이터를 받아올때 분기문을 무수히 태우곤 했는데, 활용하면 좋을것같다. 정독하기.
    우아한형제 기술블로그 - Enum 활용기
  • class Member
  • class MemberRepository
  • class MemoryMemberRepository

📌 12. 회원 도메인 개발

  • Interface MemberService
  • class MemberServiceImpl

📌 13. 회원 도메인 실행과 테스트

  • class MemberApp
    psvm
  • junit testFramework 사용
  • test class MemberServiceTEst

📌 14. 주문할인과 도메인 설계

📌 15. 주문할인과 도메인 개발

  • hello.core.discount
  • interface DiscountPolicy
  • class FixDiscountPolicy
  • interface OderService
  • class OderServiceImpl
    단일책임의 원칙을 지켜 개발.

📌 16. 주문할인과 도메인 실행과 테스트

  • class OderApp
    psvm
  • test OderServiceTest
    long, Long 차이 생각이 없었지만 문득? long null불가. 기본형 참조형. 자바 자료형에 대해 복습하면 좋을듯.

📍 3. 스프링 핵심원리 이해3 - 객체지향 원리 적용

📌 17. 새로운 할인 정책 개발

  • 애자일 소프트웨어 개발 선언
  • class RateDiscountPolicy
  • test class RateDiscountPolicyTest

📌 18. 새로운 할인적용 정책과 문제점

  • class oderServiceImpl
    • 문제 : OCP, DIP객체지향 설계원칙 준수X
    • 클라이언트인 oderServiceImpl 코드 수정. FixDiscountPolicy -> RateDiscountPolicy 변경.
    • DIP위반. OderServiceImpl은 FixDiscountPoliy를 의존하고있음.
    • 코드 변경 순간 OCP 위반.
    • 해결 : 누군가 DiscountPolicy를 주입해주어야한다.

📌 19. 관심사의 분리

  • hello.core.AppConfig.class 생성
  • memberServiceImpl 수정.
    • 생성자를 통해서 memberRepository 주입받기. 생성자주입이라고 함.
    • 추상화에만 의존하고 구체는 밖에서 주입해줌.
  • OderServiceImple도 마찬가지로 수정
    • MemberRepository, DiscountPolicy 주입받기.
      -final 키워드 사용. 아래 블로그에 정리를 잘 해두셨다.
      final - blog.lulab.net
  • MemberApp.class 수정.
    • AppConfig에서 memberService를 꺼내 사용.
  • test들 수정

📌 20. AppConfig 리팩토링

  • 중복제거
  • 역할과 구현 클래스 구성 한눈에 파악 가능.

📌 21. 새로운 구조와 할인정책 적용

  • AppConfig 구현영역. 구현영역과 사용역역이 분리됨
  • 고정할인 -> 정률할인으로 변경하고싶다 ? AppConfig만 변경하면 됨.

📌 22. 전체 흐름 정리

📌 23. 좋은 객체지향 설계의 5가지 원칙의 적용

  • SRP
    • 한 클래스는 하나의 책임만 가져야한다.
    • 기존의 service는 구현객체를 생성 연결 실행하는 다양한 책임을 가졌다.
    • 클라이언트는 실행만. AppConfig는 구현객체 생성 연결.
  • DIP
    • 추상화에 의존해야하며, 구체화에 의존하면 안된다. 의존성 주입은 DIP를 따르는 방법 중의 하나이다.
    • 기존 service는 구체화클래스에 의존했다.
    • AppConfig로 의존성을 주입해줌.
  • OCP
    • 확장에는 열려있으나 변경에는 닫혀있어야한다.
    • 클라이언트 코드를 변경하지 않도록 AppConfig에서 fix->rateDiscountPolicy로 변경.
    • 소프트웨어를 확장해도 사용영역의 변경은 닫혀있다.

📌 24. IoC, DI 그리고 컨테이너

  • 제어의 역전(Inversion of Control)
    • 기존 클라이언트에서 구현객체 생성 연결 실행하지않고,
      외부(AppConfig)에서 관리하는 것이 IoC
    • 프레임워크 vs 라이브러리 ?
      • 프레임워크가 내가 작성한 코드를 제어하고, 대신 실행
      • 내가 작성한 코드가 직접 제어흐름을 담당하면 라이브러리.
  • 의존관계 주입(Dependency Injection)
    • OderServiceImpl은 DiscountPolicy에 의존한다. 실제 어떤 구현객체가 사용될지는 모른다.
    • 의존관계는 정적인 클래스의존관계, 실행 시점에 결정되는 동적인 객체(인스턴스)의존관례를 분리해서 생각해야한다.
      • 정적 : 코드(import 등)을 보고 의존관계 파악 가능
      • 동적 : 실행 시점에 외부에서 실제구현객체를 생성하고 클라이언트에 전달. 이것이 의존관계 주입.
  • AppConfig처럼 객체를 생성하고 관리하며 의존관계를 연결해주는것이 IoC, DI 컨테이너이다.

📌 25. 스프링 전환하기

  • AppConfig @Configuration @Bean으로 스프링 컨테이너에 등록.
  • MemberApp 수정.
  • OderApp 수정

📍 4. 스프링컨테이너와 스프링 빈

📌 26. 스프링 컨테이너 생성

  • 스프링컨테이너 생성 -> 의존관계생성

📌 27. 스프링 컨테이너 생성

  • class ApplicationContextInfoTest 생성
    스프링빈, 애플리케이션빈 조회

📌 28. 스프링 빈 조회 - 기본

  • class ApplicationContextBasicFindTest 생성

📌 28. 스프링 빈 조회 - 동일한 타입이 둘 이상

  • class ApplicationContextSameBeanFindTest 생성

📌 29. BeanFactory와 ApplicationContext

  • BeanFactory
    스프링컨테이너 최상위인터페이스
  • ApplicationContext
    BeanFacotory상속받아 다양한기능제공.(국제화, 환경변수, 리소스조회 등)

📌 30. 다양한 설정형식 지원 - 자바코드, XML 등

  • test XmlAppContext 생성
  • appConfig.xml 생성

📌 31. 스프링 빈 설정 메타정보 - BeanDefinition

  • 빈 설정 메타정보=BeanDefinition
    다양한 형태의 설정정보를 BeanDefinition으로 추상화해서 사용.
    (scope, lazyInit.. 등등..)
  • test BeanDefinitionTest 생성
  • 직접적으로 빈 등록, factorybean이용 빈 등록 방법 두가지

📍 5. 싱글톤 컨테이너

📌 32. 웹 애플리케이션과 싱글톤

  • test class SingletonTest 생성

📌 33. 싱글톤 패턴

  • test class SingletonService 생성
    외부에서 객체생성 불가능.
    //3. 생성자를 private으로 선언해서 외부에서 new 키워드를 사용한 객체 생성을 못하게 막는다.
    private SingletonService() {
    }
  • test class SingletonTest_singletonServiceTest 작성
  • appConfig 내용 싱글톤으로 수정? -> 안해도되고, 스프링컨테이너가 싱클톤으로 관리. 싱글톤패턴 단점도 보완.

📌 34. 싱글톤 컨테이너

  • test class SingletonTest_springContainer 작성

📌 35. 싱글톤 방식의 문제점

  • test class StatefulService 생성
  • test class StatefulServiceTest 생성

📌 36. Configuration과 싱글톤

  • test ConfigurationSingletonTest 생성

📌 37. @Configuration과 바이트코드조작의 마법

  • @Configuration을 붙이면 바이트코드조작 라이브러리를 사용하여 Appconfig를 상속받은 임의의 클래스를 생성하여 스프링빈으로 등록한것.
    따라서 @Configurationd을 붙이면, 싱글톤을 보장.

  • 바이트코드조작 라이브러리
    if(있으면) 리턴
    없으면 생성

📍 6. 컴포넌트 스캔

📌 38. 컴포넌트스캔과 의존관계자동주입 시작하기

  • class AutoAppConfig 생성
  • @Component붙이기.
    MemorymemberRepository
    RateDiscountPolicy
    MemberServiceImpl
  • AppConfig에서는 의존관계주입 해줬는데
    AutoAppConfig에서는 생성자에 @Autowiredf 자동의존관계주입.
  • 로그
18:23:54.530 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/psy/Documents/lecture/springboot/spring2/core/out/production/classes/hello/core/discount/RateDiscountPolicy.class]
18:23:54.530 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/psy/Documents/lecture/springboot/spring2/core/out/production/classes/hello/core/member/MemberServiceImpl.class]
18:23:54.531 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/psy/Documents/lecture/springboot/spring2/core/out/production/classes/hello/core/member/MemoryMemberRepository.class]
18:23:54.531 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Identified candidate component class: file [/Users/psy/Documents/lecture/springboot/spring2/core/out/production/classes/hello/core/oder/OderServiceImpl.class]
  • 싱글톤로그
18:23:54.588 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'autoAppConfig'
18:23:54.590 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'rateDiscountPolicy'
18:23:54.591 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'memberServiceImpl'
18:23:54.599 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'memoryMemberRepository'
  • Autowired 로그
18:23:54.600 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'memberServiceImpl' via constructor to bean named 'memoryMemberRepository'
18:23:54.601 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'oderServiceImpl'
18:23:54.601 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'oderServiceImpl' via constructor to bean named 'memoryMemberRepository'
18:23:54.601 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'oderServiceImpl' via constructor to bean named 'rateDiscountPolicy'
  • Autowired 타입을기준으로 탐색

📌 39. 탐색 위치와 기본 스캔 대상

  • basePakages
  • basepakageClasses
  • default

📌 40. 필터

  • test MyIncludeComponent
  • test myExcludeComponent
  • ComponentFilterAppConfigTest
  • BeanA
  • BeanB

📌 41. 중복등록과 충돌

  • 수동빈 vs 자동빈 : 수동빈이 우선권이지만 최근부트에서는 오류

📍 7. 의존관계 자동주입

📌 42. 다양한 의존관계 주입방법

  • 생성자주입
    스프링빈 등록 시 생성자 호출할 때 주입.
  • 수정자주입(setter)
  • 필드주입
  • 일반 메서드 주입

📌 43. 옵션처리

📌 44. 생성자주입을 선택해라

  • 불변, 누락방지, final키워드

📌 45. 롬복과 최신트렌드.

  • 롬복은 라이브러리
  • 롬복설치 및 설정
  • oderserviceImpl 수정
  • @RequireArgumentConstructor
    final이 붙은것을 가지고 생성자를 자동생성

📌 46. 조회빈이 2개이상 - 문제

  • @Autowired는 타입으로조회. discounpolicy 주입시 fix, rate 두개@ComponentScan 빈등록하면. 조회빈이 2개 이상이므로 익셉션

📌 47. @Autowired 필드명, @Qualifier, @Primary

  • @Qualifier
  • @Primary

📌 48. 애노테이션 직접 만들기

  • @interface MainDiscountPolicy 생성

📌 49. 조회한 빈이 모두 필요할 때 List, Map

📍 8. 빈 생명주기 콜백

📌 50. 빈 생명주기콜백 시작

  • test NetworkClient 생성
  • test BeanLifeCycle 생성
profile
SAP CO

0개의 댓글