I\'m facing an issue trying to define a context hierarchy using AnnotationConfigApplicationContext
.
The problem is when defining a module context insid
Don't use XML for the child context. Use ctx.setParent then ctx.register. Like this:
public class ParentForAnnotationContextExample {
public static void main(String[] args) {
ApplicationContext parentContext = new AnnotationConfigApplicationContext(ParentContext.class);
AnnotationConfigApplicationContext childContext = new AnnotationConfigApplicationContext();
childContext.setParent(parentContext);
childContext.register(ChildContext.class); //don't add in the constructor, otherwise the @Inject won't work
childContext.refresh();
System.out.println(childContext.getBean(ParentBean.class));
System.out.println(childContext.getBean(ChildBean.class));
childContext.close();
}
@Configuration
public static class ParentContext {
@Bean ParentBean someParentBean() {
return new ParentBean();
}
}
@Configuration
public static class ChildContext {
@Bean ChildBean someChildBean() {
return new ChildBean();
}
}
public static class ParentBean {}
public static class ChildBean {
//this @Inject won't work if you use ChildContext.class in the child AnnotationConfigApplicationContext constructor
@Inject private ParentBean injectedFromParentCtx;
}
}