【问题标题】:What is the Spring DI equivalent of Dagger2 Subcomponents什么是 Dagger2 子组件的 Spring DI 等效项
【发布时间】:2020-05-04 14:16:23
【问题描述】:

Dagger2 有子组件https://medium.com/tompee/dagger-2-scopes-and-subcomponents-d54d58511781 用于使用生命周期比主应用程序更短的 DI,例如,如果您有一个作业服务,那么该服务将为每个作业提供一个带有子组件的组件。

Spring 的 DI 框架的等价物是什么?

【问题讨论】:

    标签: java spring spring-boot dependency-injection dagger-2


    【解决方案1】:

    我能看到的唯一可能性是使用上下文层次结构并手动处理生命周期较短的上下文。

    // Does Dagger's @Subcomponent.Factory work
    public class JobExecutor {
        private final ApplicationContext mainApplicationContext;
    
        @Inject
        public JobExecutor(ApplicationContext mainApplicationContext) {
            this.mainApplicationContext = mainApplicationContext;
        }
    
        public Result execute(Job job) {
            AnnotationConfigApplicationContext jobContext = null;
            try {
                jobContext = new AnnotationConfigApplicationContext();
                jobContext.setParent(mainApplicationContext); // Provides access to common beans
                jobContext.register(SpringJobContext.class);
                jobContext.getBeanFactory().registerSingleton("job", job); // Does Dagger's @BindsInstance work
                jobContext.refresh();
                // You can access and execute one of the beans from jobContext manually or use @PostConstruct
                return jobContext.getBean(JobExecutorFromJobContext.class)
                        .execute();
            } finally {
                if (jobContext != null) {
                    jobContext.destroy();
                }
            }
        }
    
        static class JobExecutorFromJobContext {
            private final Database database; // From parent's context
            private final Job job;
    
            @Inject
            JobExecutorFromJobContext(Database database, Job job) {
                this.database = database;
                this.job = job;
            }
    
            public void execute() {
                // ...
            }
        }
    }
    

    【讨论】:

    • 变成了一个看起来很干净的包装函数(尤其是在 kotlin 中),这是我缺少的 setParent 谢谢!
    猜你喜欢
    • 2010-09-14
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 2012-12-27
    • 2018-11-12
    • 2012-10-16
    • 2010-10-01
    相关资源
    最近更新 更多