简体   繁体   中英

Annotations based configuration hierarchy

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?

For this to work, your child context should import the parent context, eg:

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM