Java_@Bean/@Configuration

Minki CHO·2023년 1월 26일
0

CodeStates

목록 보기
28/43

@Bean and @Configuration

자바 기반 설정의 가장 중요한 애너테이션
@Configuration
@Bean
:메서드가 스프링 컨테이너에서 관리할 새 객체를 인스턴스화, 구성 및 초기화한다는 것을 나타내는데 사용됨

//DependencyConfig 클래스
//컨텍스트를 인스턴스화할 때
@Configuration
public class DependencyConfig {

    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

-AnnotationConfigApplicationContext를 사용해 스프링 컨테이너를 인스턴스화하는 방법
(인스턴스화: 클래스로부터 객체를 만드는 과정/ 특징으로는 클래스가 가지고 있는 메서드를 모두 상속받음)

=애너테이션을 이용해 Config 클래스 설정하는 방법
:ApplicationContext 구현은
아래 애너테이션이 달린 클래스로 파라피터를 전달받고 있음
1) @Configuration 클래스
2) @Component 클래스
3) JSR-330 메타데이터

:@Configuration 클래스가 입력으로 제공되면<노이해중>
@Configuration 클래스 자체가 Bean 정의로 등록되고
클래스 내에서 선언된 모든 @Bean 메서드도 Bean 정의로 등록됨

@Bean 애너테이션

:메서드 레벨 애너테이션
:@Configuration or @Component 가 적용된 클래스에서 사용할 수 있음

-빈 선언
:@Bean 애너테이션을 메서드에 추가해서 Bean으로 정의/선언할 수 있음

@Configuration
public class DependencyConfig {

    @Bean
    public TransferServiceImpl transferService() {
        return new TransferServiceImpl();
    }
}

-빈 의존성
:@Bean 애너테이션이 추가된 메서드는
빈을 구축하는데 필요한 의존성을 나타내는데에 매개변수를 사용할 수 있음

@Configuration
public class DependencyConfig {

    @Bean
    public TransferService transferService(AccountRepository accountRepository) {
        return new TransferServiceImpl(accountRepository);
    }
}

@Configuration 애너테이션을 사용하기

:해당 객체가 bean definitions(빈 설정 메타데이터)의 소스임을 나타내는 애너테이션
:@Bean-annoted 메서드를 통해 bean을 선언
:@Configuration 클래스의 @Bean 메서드에 대한 호출을 사용하며 bean 사이의 의존성을 정의할 수도 있음

-Bean 사이에 의존성 주입
:빈이 서로 의존성을 가질 때, 의존성을 표현하는 것을 다른 bean 메서드를 호출하는 것처럼 간단함
ex.
beanOne은 생성자 주입을 통해 beanTwo에 대한 참조를 받음

@Configuration
public class DependencyConfig {

    @Bean
    public BeanOne beanOne() {
        return new BeanOne(beanTwo());
    }

    @Bean
    public BeanTwo beanTwo() {
        return new BeanTwo();
    }
}
profile
Developer

0개의 댓글