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, e.g.:
@Configuration
@Import(ParentContextConfig.class)
public class ChildContextConfig{
@Autowired parentBeanOne
...
}
Refer to the spring docu about @Configuration for more infos.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With