Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotations based configuration hierarchy

Tags:

java

spring

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?

like image 564
Rafael Avatar asked Mar 21 '11 09:03

Rafael


1 Answers

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.

like image 193
Fritz Duchardt Avatar answered Oct 14 '22 03:10

Fritz Duchardt