Bivas Bivas - 1 year ago 225
Java Question

AnnotationConfigApplicationContext and parent context

I'm facing an issue trying to define a context hierarchy using


The problem is when defining a module context inside
and setting the 'parent' property with another context (XML/Annotated based).


beanRefContext.xml in module A

<bean id="moduleA_ApplicationContext"
<property name="configLocations">


<bean id="dataSource"

<!-- Hibernate Session Factory -->
<bean name="sessionFactory"
<property name="dataSource" ref="dataSource"/>
<property name="useTransactionAwareDataSource" value="true"/>
<property name="packagesToScan">
<property name="hibernateProperties">
<!-- hibernate props -->

beanRefContext.xml in module B

<bean id="moduleB_ApplicationContext"
class="org.springframework.context.annotation.AnnotationConfigApplicationContext" >
<property name="parent" ref="moduleA_ApplicationContext"/>


class FooHibernateDao implements FooDao {
private SessionFactory sessionsFactory;

// CRUD methods

Module B application context fails to find bean defined in module A application context.

From looking at the code of
it seems that the scanning process doesn't use the parent as a reference to resolve beans.

Is there something I'm doing wrong or my attempt to create a hierarchy is impossible with annotation configuration?

Answer Source

The problem stems from the fact that the constructor of the AnnotationConfigApplicationContext does the scan. Thus the parent is not set at this stage, it is only set after the scan is done as the parent is set by a property - thus the reason why it does not find your bean.

The default AnnotationConfigApplicationContext bean does not have a constructor that takes a parent factory - not sure why.

You can either use the normal xml based application context and configure your annotation scanning in there or you can create a custom fatory bean that will do create the annotation application context. This would specify the parent reference and then do the scan.

Take a look at the source...

The factory would look like this:

public class AnnotationContextFactory implements FactoryBean<ApplicationContext> {

private String[] packages;
private ApplicationContext parent;

public ApplicationContext getObject() throws Exception {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    return context;

public Class<ApplicationContext> getObjectType() {
    return ApplicationContext.class;

public boolean isSingleton() {
    return true;

public void setPackages(String... args) {
    this.packages = args;

public void setParent(ApplicationContext parent) {
    this.parent = parent;

And your bean definition:

<bean id="moduleB_ApplicationContext" class="">
    <property name="parent" ref="moduleA_ApplicationContext" />
    <property name="packages">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download