본문 바로가기

개발일기/Spring

[Spring] ApplicationContext

728x90
반응형

ApplicationContext란?

-> ApplicationContext는 보통 스프링 컨테이너라고 한다. 스프링컨테이너에 저장한 스프링 빈을 불러올때 사용한다.

간단한 예를 보면 , 

 

@Configuration
public class MyConfig {

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

    	@Bean
    	public MyRepository myRepository() {
        	return new MyRepositoryImpl();
    	}
    }

# 해당 코드를 보면 MyConfig 라는 class를 @configuration 어노테이션을 이용하여 스프링 컨테이너로 지정하고,

 @Bean어노테이션을 통해 MyService , MyRepository 라는 두개의 함수를 스프링 빈 저장소에 저장을 하였다.

 

public class MyApp {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        MyService myService = applicationContext.getBean("myService" , MyService.class);
    }
}

# 그리고, ApplicationContext를 이용하여 위에서 지정한 스프링 컨테이너를 불러오고 그 스프링컨터이너에 저장된 스프링 빈을 빈 이름으로 불러온다.

# 빈의 이름인 아무것도 지정하지 않았을때는 해당 함수의 이름으로 지정이된다.

# 빈의 이름은 중복이 있어서는 안된다.

728x90
반응형

'개발일기 > Spring' 카테고리의 다른 글