prosource

Application Context Aware는 봄에 어떻게 작동합니까?

probook 2023. 3. 14. 21:43
반응형

Application Context Aware는 봄에 어떻게 작동합니까?

봄에 콩이 실장되면ApplicationContextAware에 액세스 할 수 있습니다.applicationContext따라서 다른 콩을 얻을 수 있습니다.

public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;     

    public void setApplicationContext(ApplicationContext context) throws BeansException {
      applicationContext = context;
    }

    public static ApplicationContext getApplicationContext() {
      return applicationContext;
    }
}

그리고나서SpringContextUtil.getApplicationContext.getBean("name")"이름"을 얻을 수 있습니다.

이렇게 하려면 이걸 넣어야 돼요.SpringContextUtil내부applications.xml,예.

<bean class="com.util.SpringContextUtil" />

여기 콩이 있다SpringContextUtil속성을 포함하지 않음applicationContext봄콩이 초기화되면 이 속성이 설정되는 것 같아요.하지만 어떻게 해야 할까요?방법은?setApplicationContext호출을 받습니까?

봄은 콩을 인스턴스화할 때 다음과 같은 인터페이스를 찾습니다.ApplicationContextAware그리고.InitializingBean검출되면 메서드가 호출됩니다.예: (매우 심플)

Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) {
    ((ApplicationContextAware) bean).setApplicationContext(ctx);
}

새로운 버전에서는 스프링 고유의 인터페이스를 구현하는 것보다 주석을 사용하는 것이 더 나을 수 있습니다.이제 간단하게 다음을 사용할 수 있습니다.

@Inject // or @Autowired
private ApplicationContext ctx;

Application Context Aware 작동 방식을 설명하는 스프링 소스 코드
사용할 때ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AbstractApplicationContext클래스,refresh()method의 코드는 다음과 같습니다.

// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);

이 메서드를 입력합니다.beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));는 ApplicationContextAwareProcessor를 AbstractrBeanFactory에 추가합니다.

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // Tell the internal bean factory to use the context's class loader etc.
        beanFactory.setBeanClassLoader(getClassLoader());
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
        // Configure the bean factory with context callbacks.
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
...........

봄이 되면 콩이 들어옵니다.AbstractAutowireCapableBeanFactory, 방식으로는initializeBean,불러applyBeanPostProcessorsBeforeInitialization콩 포스트 프로세스를 구현합니다.프로세스에는 application Context를 주입하는 것이 포함됩니다.

@Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            result = beanProcessor.postProcessBeforeInitialization(result, beanName);
            if (result == null) {
                return result;
            }
        }
        return result;
    }

예를 들어 BeanPostProcessor가 postProcessBeforeInitialization 메서드를 실행하기 위해 객체를 구현하는 경우ApplicationContextAwareProcessor추가되어 있습니다.

private void invokeAwareInterfaces(Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof EnvironmentAware) {
                ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
            }
            if (bean instanceof EmbeddedValueResolverAware) {
                ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
                        new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
            }
            if (bean instanceof ResourceLoaderAware) {
                ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
            }
            if (bean instanceof ApplicationEventPublisherAware) {
                ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
            }
            if (bean instanceof MessageSourceAware) {
                ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
            }
            if (bean instanceof ApplicationContextAware) {
                ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
            }
        }
    }

실행 중인 ApplicationContext에 대한 알림을 받는 개체에 의해 구현되는 인터페이스.

위의 내용은 Spring 문서 웹사이트 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html에서 발췌한 것입니다.

그래서 스프링 컨테이너가 가동되면 그 때 뭔가 하고 싶은 일이 있으면 호출되는 것 같았습니다.

콘텍스트를 설정하는 방법은 하나뿐이기 때문에, 콘텍스트를 취득해, 이미 콘텍스트에 들어가 있는 것에 대해 뭔가 조치를 취할 수 있다고 생각합니다.

ApplicationContextAware Interface: 스프링 컨테이너 서비스를 호출할 수 있는 현재 응용 프로그램콘텍스트클래스에서 아래 메서드로 주입된 현재 applicationContext 인스턴스를 가져올 수 있습니다.

public void setApplicationContext(ApplicationContext context) throws BeansException.

언급URL : https://stackoverflow.com/questions/21553120/how-does-applicationcontextaware-work-in-spring

반응형