ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링으로 전환하기
    FrameWork/Spring&Spring-boot 2021. 12. 31. 19:47

    드디어! 그날이 왔군

     

    -지금까지 순수한 자바 코드만으로DI를 적용했다. 이제 스프링을 사용해 보자

     

    AppConfig 스프링기반으로 변경

     

    @Configuration : 어플리케이션의 설정·구성정보를 담당하는 class에 붙는 annotation

    @Bean : 스프링 컨테이너에 담을 객체를 생성하는 메서드에 붙는 annotation

    package hello.core;
    
    import hello.core.member.Grade;
    import hello.core.member.Member;
    import hello.core.member.MemberService;
    import hello.core.member.MemberServiceImpl;
    import hello.core.order.Order;
    import hello.core.order.OrderService;
    import hello.core.order.OrderServiceImpl;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class OrderApp {
    
        public static void main(String[] args) {
    
           // AppConfig appConfig = new AppConfig();
    
            //MemberService memberService = appConfig.memberService();
            //OrderService orderService = appConfig.orderService();
    
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
    
            MemberService memberService = applicationContext.getBean("memberService", MemberService.class);
            OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
    
    
            Long memberId = 1L;
            Member member = new Member(memberId, "memberA", Grade.VIP);
            memberService.join(member);
    
            Order order = orderService.createOrder(memberId, "itemA", 20000);
    
            System.out.println("order ="+order);
    
    
        }
    }
    

     

    • 두 코드를 실행하면 스프링관련 로그가 몇줄 실행되면서 기존과 동일한 결과가 출력된다.

     

     

    스프링 생성

    ->스프링은 모든 것이 ApplicationContext라는 것으로 시작을 한다. 즉 ApplicationContext를 스프링 컨테이너 라고 보면 된다. ApplicationContext가 모든 것을 관리한다.

     

    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

    실제 annotation을 기반으로 config를 하고 있는 class(AppConfig)를 생성자의 파라미터로 넣어 준다. 이렇게 하면 AppConfig에 있는 그 환경 설정 정보를 가지고, 스프링이 @Bean이 있는 메소드 스캔한다. 그리고 메소드를 통해 스프링이 생성한 객체를 스프링컨테이너(스프링빈)에 다 집어 넣어서 관리한다.

     

    AppConfig appConfig = new AppConfig();
    MemberService memberService = appConfig.memberService();

    기존에, AppConfig객체를 직접 찾아 오던 방식에서 벗어나 스프링컨테이너를 통해서 원하는 객체를 찾아 온다.

     

    ->스프링 컨테이너에 

    @Bean을 통해 생성되는 객체는 기본적으로 이름이 메서드 명으로 등록이 된다.

    MemberService memberService = applicationContext.getBean("memberService", MemberService.class);

    *MemberService memberSErvice = applicationContext.getBean( 찾아오고 싶은 객체 이름 , 찾아오고 싶은 객체 타입 );

     

    스프링이 내부적으로 필요해서 등록하는 bean

     

    AppConfig에 작성한 @Bean 메서드들이 key는 메서드 이름 value는 return(new 객체 인스턴스)값으로 해서 스프링컨테이너에 객체로 생성돼 등록된느 모습을 확인 할수 있다.

     

    객체가 필요하면 위와 같은 방법으로 스프링 컨테이너에서 이름을 주고 꺼내면, 된다.

     

    *스프링 컨테이너*

    • 'ApplicationContext'를 스프링 컨테이너 한다.

    + 현재 작업하는 앱의  전체 context(문맥)이라고 생각하면 된다.

    • 기존에는 개발자가 'AppConfig'를 사용해서 직접 객체를 생성하고  DI를 했지만, 이제부터는 스프링 컨테이너를 통해서 사용한다.
    • 스프링 컨테이너는 '@Configuration'이 붙은 'AppConfig'를 설정(구성)정보로 사용한다. 여기서'@Bean'이라 적힌 메서드를 모두 호출해서 반환된 객체를 스프링 컨테이너에 등록된다. 이렇게 스프링 컨테이너에 등록된 객체를 스프링 빈이라 한다.
    • 스프링 빈은 '@Bean'이 붙은 메서드 명을 스프링 빈의 이름으로 사용한다.('memberService','orderService')
    @Bean(name="changeName")
    public MemberService memberService(){
        return new MemberServiceImpl(memberRepository());
    } //물론, annotation 속성을 사용해서 객체 이름을 바꾸는 것도 가능하다.
    • 이전에는 개발자가 필요한 객체를 'AppConfig'를 사용해서 직접 조회했지만, 이제부터는 스프링 컨테이너를 통해서 필요한 스프링 빈(객체)를 찾아야 한다. 스프링 빈은'applicationContxt.getBean( )'메서드를 사용해서 찾을 수 있다.
    • 기존에 개발자가 직접 자바코드로 모든 것을 했었다면 이제부터 스프링 컨테이너에 객체를 스프링 빈으로 등록하고, 스프링 컨테이너에서 스프링 빈을 찾아서 사용하도록 변경되었다.

    +개발자가 직접 AppConfig를 만드는게 아니라 스프링 컨테이너를 통해서, 어떤 프로젝트에서도 DI와 같은 것들을 스프링컨테이너가 편리하게 해주도록 범용의 프레임워크가 생긴것

     

    -스프링 컨테이너를 사용하면 어떤 장점이 있을까?

    DIP,OCP,다형성

     

     

    [출처 : 김영한. 스프링 핵심 원리-기본편. 인프런]

     

    댓글

Designed by Tistory.