7

We use @Configuration classes to do Java based Spring configuration. I am trying to set up a Hierarchy of AnnotationConfigApplicationContext(s).

It seems to work. As I can Autowire beans from parent context as members of beans created from one of the child contexts.

However I am not managing to Autowire beans from the parent context to the @Configuration class files, something that is very handy. They are all null.

// parent context config
@Configuration
public class ParentContextConfig{
  @Bean parentBeanOne...
  @Bean parentBeanTwo...
}

// child context config
@Configuration
public class ChildContextConfig{
  @Autowired parentBeanOne

  @Bean childBeanOne...
}

// a sample bean
@Component
public class ChildBeanOne{
  @Autowired parentBeanTwo
}

In this sample, what I am getting is parentBeanTwo properly created while parentBeanOne is not autowired (null) to the config file.

What am I missing?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Rafael
  • 585
  • 1
  • 6
  • 17
  • How have you set up the parent/child relationship? – skaffman Mar 21 '11 at 10:26
  • I have found that autowiring to ChildContexts works if you declare those AnnotationConfigApplicationContext as beans on the parent context. However I start getting "circular references?" related exceptions... I cannot identify any circular reference. – Rafael Mar 21 '11 at 11:42
  • I set the relationship by doing setParent(ctx) before registering the @configurable config classes. – Rafael Mar 21 '11 at 11:43
  • More info https://stackoverflow.com/questions/7774295/spring-xml-file-configuration-hierarchy-help-explanation – pramodc84 Feb 13 '18 at 08:39

3 Answers3

1

For this to work, your child context should import the parent context, e.g.:

@Configuration
@Import(ParentContextConfig.class)
 public class ChildContextConfig{
    @Autowired parentBeanOne
    ...
  }

Refer to the spring docu about @Configuration for more infos.

Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60
0

As of Spring 3.2.2, Spring now supports this with @ContextHierarchy. http://docs.spring.io/spring-framework/docs/3.2.x/javadoc-api/org/springframework/test/context/ContextHierarchy.html

Ryan Walls
  • 6,962
  • 1
  • 39
  • 42
0

I think Spring wants you to use standard Java hierarchy rules in order to establish the parent child relationships of configuration Objects. That is, have the child config class extend the parent config class.

dough
  • 714
  • 5
  • 14
  • Yeahh, but that is not exactly the same thing. As the whole class hierarchy will be in the same Spring Context. In some cases you want a child context accessing a parent context, and not the other way around, such as with servlet containers, etc. – Rafael Mar 30 '11 at 12:01
  • 1
    is there any new development on this? It seems as a basic configuration requirement. – Eugen Nov 15 '11 at 15:40