Program Tip

ApplicationContextAware는 Spring에서 어떻게 작동합니까?

programtip 2020. 11. 5. 18:52
반응형

ApplicationContextAware는 Spring에서 어떻게 작동합니까?


봄에 빈이를 구현 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;

In class
를 사용할 때 ApplicationContextAware가 어떻게 작동하는지 설명하는 Spring 소스 코드 는 다음과 같은 코드를 가지고 있습니다.ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AbstractApplicationContextrefresh()

// 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));
...........

Spring에서 bean을 초기화하면 AbstractAutowireCapableBeanFactory메소드 에서 bean 포스트 프로세스를 구현하도록 initializeBean호출 applyBeanPostProcessorsBeforeInitialization합니다. 이 프로세스에는 applicationContext 주입이 포함됩니다.

@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가 Object를 구현하여 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);
            }
        }
    }

ApplicationContextAware Interface ,the current application context, through which you can invoke the spring container services. We can get current applicationContext instance injected by below method in the class

public void setApplicationContext(ApplicationContext context) throws BeansException.

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

반응형