我想将以下基于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对象注入其配置中。
答案 0 :(得分:2)
单独的@Configuration
类来隔离“非标准”对象?
@Configuration
public class ConfigA {
public @Bean User getUser () {
// Here do whatever it takes to create/lookup the user
return new User();
}
}