AnnotationConfigApplicationContext and parent context

后端 未结 5 683
暖寄归人
暖寄归人 2021-01-03 05:29

I\'m facing an issue trying to define a context hierarchy using AnnotationConfigApplicationContext.

The problem is when defining a module context insid

5条回答
  •  感情败类
    2021-01-03 06:17

    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;
        }
    }
    

提交回复
热议问题