java - Spring DI 使用无法 beanified 的遗留对象

标签 java spring dependency-injection guice

我想将以下基于 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 对象注入(inject)到其配置中。

最佳答案

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

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

关于java - Spring DI 使用无法 beanified 的遗留对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9714348/

相关文章:

java - @Transactional 和 @Transactional(readOnly=true) 有什么区别

c# - 具有多个接口(interface)的 Autofac Open Generic Decorator 导致循环依赖解析

java - 仅当不存在 key1=value1 且 key2=value3 的另一个文档时,如果 key1=value1 且 key2=value2 则从弹性获取所有文档

java - 为什么 'gradle install' 会用 'unspecified' 替换我的版本?

java - Eclipse javax.websocket 导入未解决

Spring imap-idle-channel-adapter 基于 Java 的配置

java - ASM 在 .class 文件中搜索字符串

spring - 在 Spring Boot 执行器中设置 endpoints.health.sensitive=false 时无效

java - 是否可以同时@inject guice ctor和成员?

dependency-injection - 在调用 bootstrap() 之前如何访问 angular2 的 Http 服务?