본문 바로가기
BackEnd/Spring

[Spring] 스프링(Spring) 핵심 기술 이야기 2부 - @Autowire

by 뽀뽀이v 2020. 9. 16.

이 글은 백기선 님의 스프링 프레임워크의 핵심 기술 강의를 듣고 복습 차원에서 적은 글입니다.

 

@Autowired

필요한 의존 객체의 "타입"에 해당하는 빈을 찾아 주입한다.

다음 위치에 사용할 수 있다. 

@Service
public class BookService {
    // 필더
    @Autowired
    BookRepository bookRepository;

    // 생성자 (스프링 4.3 부터는 생략 가능)
    @Autowired
    public BookService () {

    }

    // Setter
    // @Autowired(required = false) -> 의존성 주입이 되지 않아도 어플리케이션이 구동된다.
    @Autowired
    public void setBookRepository(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
}

 

  • 해당 타입의 빈이 없는 경우 => 에러 발생
  • 해당 타입의 빈이 한 개인 경우 => 정상처리
  • 해당 타입의 빈이 여러 개인 경우 => @Primary, @Qualifier, 해당 타입의 빈 모두 주입 가능하다.
@Repository @Primary
public class MyBookRepository implements BookRepository {
}
@Service
public class BookService {
    @Autowired
    List<BookRepository> bookRepositories;

    public void printBookRepository() {
        this.bookRepositories.forEach(System.out::println);
    }
}

Spring Bean LifeCycle

Bean 생성과 소멸에 대한 부분을 메서드로 구현할 수 있습니다. 

Initialize 메서드

Initialize 메서드는 Bean 객체가 생성되고 DI를 마친 후 실행되는 메서드입니다. DI를 통해 Bean이 주입된 후에 초기화할 작업이 있다면 초기화 메서드를 이용해서 초기화를 진행할 수 있습니다. 일반적으로는 생성자를 통해 초기화합니다.

 

  • @PostConstruct
@Repository
public class WeBookRepository implements BookRepository {
    @PostConstruct
    public void postConstruct() {
        System.out.println("WeBookRepository postConstruct");
    }
}

 

  • InitializeBean
@Service
public class BookService implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("BookService postConstruct");
    }
}

 

  • Bean(initMethod)
@Configuration
public class BeanConfiguration {
    @Bean(initMethod = "init")
    public BookBean bookBean() {
        return new BookBean();
    }

    public static class BookBean {
        public void init() throws Exception {
            System.out.println("init bookBean");
        }
    }
}

 

Destroy 메서드

Destory 메서드는 스프링 컨테이너가 종료될 때, 호출되어 Bean이 사용한 리소스들을 반환하거나 종료 시점에 처리해야 할 작업이 있을 경우 사용합니다.

 

  • @PreDestroy
@Repository
public class MyBookRepository implements BookRepository {
    @PreDestroy
    public void preDestroy() {
        System.out.println("MyBookRepository postConstruct");
    }
}

 

  • DisposableBean
@Service
public class BookService implements DisposableBean {
    @Override
    public void destroy() throws Exception {
        System.out.println("BookService postConstruct");
    }
}

 

  • @Bean(destroyMethod)
@Configuration
public class BeanConfiguration {
    @Bean(destroyMethod = "destroy")
    public BookBean bookBean() {
        return new BookBean();
    }

    public static class BookBean {
        public void destroy() throws Exception {
            System.out.println("init bookBean");
        }
    }
}

댓글