gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:51:38 26 4
gpt4 key购买 nike

我想将以下基于 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com