【问题标题】:Spring DI using legacy objects that can't be beanifiedSpring DI 使用无法被 bean 化的遗留对象
【发布时间】:2012-03-15 05:14:23
【问题描述】:

我想将以下基于 Guice 的 DI 配置转换为基于 Spring Java-config 的 DI。

public class UserModule extends AbstractModule {

    private final User user;

    public UserModule(User user) {
        this.user = user;
    }

    @Override
    protected void configure() {
       // don't need to do any configuration
    }

    @Provides @Singleton
    User provideUser() {
        return user;
    }

    @Provides @Singleton @Inject
    UserStorageService provideUserStorageService(User u) {
        return new UserStorageServiceImpl(u);
    }
}

然后是预期用途

Injector userOneInjector = Guice.createInjector(new UserModule(userOne));
Injector userTwoInjector = Guice.createInjector(new UserModule(userTwo));

不幸的是,Spring 的 AnnotationConfigApplicationContext 接受的是配置类而不是对象,所以我不确定如何将 User 对象注入到其配置中。

【问题讨论】:

    标签: java spring dependency-injection guice


    【解决方案1】:

    一个单独的@Configuration 类来隔离“非标准”对象?

    @Configuration
    public class ConfigA {
        public @Bean User getUser () {
            // Here do whatever it takes to create/lookup the user
            return new User();
        }
    }
    

    【讨论】:

    • 但是创建/查找 CannotBeBeanified 需要使用配置范围之外的对象。使用 Guice,我可以将它们作为构造函数参数传递,试图弄清楚如何使用 Spring 来做到这一点。例如,如果 CannotBeBeanified 构造函数使用了仅在运行时可用的字符串或文件怎么办?
    • 配置范围之外的意思是什么?
    • 对不起,我认为我的评论写得不好。我已经更新了问题中的示例,希望它更清楚?在新示例中,我不想创建新用户,我想使用我已经引用的对象,但是如果不使用单例,我不知道如何做到这一点。
    • 我想我明白了。您想基于现有的User 对象创建UserModule 对象吗? Users 来自哪里?
    • 是的!假设Users 来自远程请求public interface ExposedViaRestOrSomething { void doSomethingFunkyWithUser(User u); }
    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多