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.
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.
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
精彩评论