Jimmy Jimmy - 4 months ago 38
Java Question

How does ApplicationContextAware work in Spring?

In spring, if a bean implements

ApplicationContextAware
, then it is able to access the
applicationContext
. Therefore it is able to get other beans.
e.g.

public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;

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

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


Then
SpringContextUtil.getApplicationContext.getBean("name")
can get the bean "name".

To do this, we should put this
SpringContextUtil
inside the
applications.xml
, e.g.

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


Here the bean
SpringContextUtil
doesn't include the property
applicationContext
. I guess when spring bean initialize, this property is set. But how is this done? How does the method
setApplicationContext
get called?

Answer

When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware and InitializingBean. If they are found, the methods are invoked. E.g. (very simplified)

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

Note that in newer version it may be better to use annotations, rather than implementing spring-specific interfaces. Now you can simply use:

@Inject // or @Autowired
private ApplicationContext ctx;
Comments