Post

Spring 의존성 주입(DI) 소개: Bean 등록과 @Autowired 활용법

의존성 주입이 왜 필요할까?


Spring 에서는 의존성 주입 (DI 라고한다) 이 제일 큰 Spring 의 특징이라고 말할수 있다. 아주 쉽게 예를 들면

1
2
3
4
5
6
class Employee {
    Employer employer;
    public Employee (){
        this.employer = new Employer();
    }
}

이런 코드가 있다고 해보자! Employee 는 항상 안에서 새로운 employer를 만들고 있다. 즉 Employer 에 의존하고 있다고 할 수 있다. 하지만 위처럼 코드를 짜면 Employer 를 extend 한 다른 class 를 받을 수 없고 new Employer 로 선언이 되었기에 Class 간의 관계가 생겨버린다. 따라서 요렇게 코드를 변화 시켜 보면

1
2
3
4
5
6
class Employee {
    Employer employer;
    public Employee (Employer employer){
        this.employer = employer;
    }
}

이렇게 변화한다. 이걸 바로 의존성 주입이라고 하며 이렇게 코드를 변화하면 우리가 원하는 employer 를 넣어줄수 있으니 결합도가 상당히 떨어지고 도 Mock 객체를 넣을수 있어서 junit test 도 훨씬 간단해지고 아주 다양한 장점이 있다!

의존성 주입 해보기, Bean


Spring 에서는 이 의존성 주입을 매우 쉽게 할 수 있도록 했다. 의존성 주입을 당하는 class (위에서 employer) 를 Bean 에 등록을 한다. Bean 에 등록하는 방법은 여러가지가 있다.

  1. Annotation 붙이기
    1
    2
    3
    4
    
    @Component
    class Employer {
     ...
    }
    

    이렇게 하면 아주 손쉽게 Employer 을 Bean 에 등록 할 수 있다. (Service(서비스), Controller (표현), Repository(DAO) 모두 가능하며 역할도 같은데 편의상 나누어 놓은 것이다!) 이 방법을 우리는 제일 많이 사용한다.

  2. resource 폴더의 application.xml 에 추가하기
    1
    2
    3
    4
    5
    6
    
     <?xml version="1.0" encoding="UTF-8"?>
     <beans>
         <bean id="Employer"
             class="com....Employer">
         </bean>
     </beans>
    
  3. ApplicationConfig.java 에서 설정해주기
    1
    2
    3
    4
    5
    6
    7
    8
    
     @Configuration 
     public class ApplicationConfig {
         @Bean
         public Employer employer() {
             Employer employer = new Employer();
             return employer;
         }
     }
    

Bean 에 등록된 객체들은 모두 Singleton 처럼 동작하게 된다!

Bean 사용하기


이제 Bean 에 등록을 했으면 이제 Employee class 에서 사용을 하면 된다.

1
2
3
4
5
6
7
8
class Employee {
    Employer employer;

    @Autowired
    public Employee (Employer employer){
        this.employer = employer;
    }
}

이렇게도 쓸수 있다

1
2
3
4
class Employee {
    @Autowired
    Employer employer;
}

하지만 spring 공식문서에서는 생성자(Constructor) 에서 주입하는것을 권장한다고 한다!

This post is licensed under CC BY 4.0 by the author.

© 병욱. Some rights reserved.