상세 컨텐츠

본문 제목

ApplicationContext

JAVA/Spring

by 영공쁘이 2023. 8. 9. 17:35

본문

의존성 빈 주입(Autowired)를 할 수 있는 환경이 아닌 곳에서 해당 객체를 가져와야 할 경우가 있다.

객체에 빈을 주입할 때 사용하는 클래스가 있다.

 

인터페이스: ApplicationContextAware

빈이 실행되는 환경인 ApplicationContext 인스턴스에 접근할 수 있도록 함.

 

*ApplicationContext  : BeanFactory의 하위 인터페이스. 스프링 컨테이너(=싱글톤 컨테이너) 라고 한다.

스프링 컨테이너 내부에는 빈 저장소가 존재한다. 빈 저장소는 key로 빈 이름을 가지고 있으며, value로 실제 빈 객체를 가지고 있다. 다음 코드를 예시로 설명이 성립이 된다.

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
   	 applicationContext = ctx;
  	}

  	public static ApplicationContext getApplicationContext() {
   	 return applicationContext;
  	}

//**예시
 	public static <T> T getBean(Class<T> c) {
 	 return applicationContext.getBean(c);
  	}
    
//**예시2
   public static <T> T getBean(String name, Class<T> c) {
    return applicationContext.getBean(name, c);
   }
}

new ApplicationContext()로 스프링 컨테이너를 만들어주면서 빈 저장소가 생성됨

 > 그 후에는, **예시 처럼 getBean을 통해 해당 주입으로 가져올 객체에 대한 클래스를 지정해 다른 곳에서 쓸 수가 있다.

그러면 @Bean 어노테이션 메서드를 실행하며 빈이 등록 됨

 

**예시2 처럼, 이름과 클래스를 가지고 빈등록을 할 수 있음.(이름은 예를 들어, 서비스의 이름이 될 경우)

 

@Service("subSvc")
public class SubServiceImpl implements SubService {
     ... // 
 }

위처럼, subSvc를 이름으로 가지고 오고 클래스는 SubService.class로 가져오면 된다. 예시는 다음과 같다.

@Data
public class SubParam extends Pagination {
	
    private int sub1;
    private String subNm;
    
    public String subNmNo(){
    	SubService subService = ApplicationContextUtil.getBean("subSvc", SubService.class);
        return subService.method1(subNm);
    }

}

* public String subNmNo()처럼,  getBean을 기존 util에서 가져와 이름과 클래스로 정의를 하면, 빈이 등록이 됨

(객체에서 의존성 주입이 어려울 때, getBean을 통해 빈 저장소의 빈을 등록하고 해당 클래스의 메서드를 사용할 수 있게 됨)

'JAVA > Spring' 카테고리의 다른 글

API와 VUE단 분리하여 배포 후 파일 수정/추가 시 설정  (0) 2024.09.20
X-Frame-Options 헤더 deny 발생 시  (0) 2023.10.18
PostConstruct 어노테이션  (0) 2023.06.19
Security_간단설명  (2) 2023.05.22
socket 통신  (0) 2023.05.17

관련글 더보기