可能是它的副本,请随意标记...我是Spring的新手。
我正在实施UserService以获取来自不同供应商的用户详细信息, 所以我的班级结构是
界面UserService - >> UserServiceA,UserServiceB
使用哪种用户服务取决于名为provider的字段。我的代码看起来像
public interface ExternalUserService {
ExternalUserDTO getUserDetail(String username);
}
实施 -
public class GoogleUserService implements ExternalUserService{
@Override
public ExternalUserDTO getUserDetail(String username) {
return user;
}
}
public class FacebookUserService implements ExternalUserService{
@Override
public ExternalUserDTO getUserDetail(String username) {
return user;
}
}
我想以这种方式在我的代码中使用它,我不知道这是否可行,但试着看看它是否可能
public class ExternalUserManager(String provider) {
String provider;
@Autowired
ExternalUserService service; //This is supposed to come from some factory, dont know how to get it in spring context.
public void doSomething(String username) {
System.out.println(service.getUserDetail(username));
}
}
Had it been in conventional java programming, I would have created a Factory called UserServiceFactory, which would have made the things straight.
Can someone please help me on how much it is possible with spring, and if its possible, then how can I achieve it? We use Spring boot, so no xml config.
答案 0 :(得分:0)
您可以使用@Bean带注释的方法和范围'原型'作为一个工厂。 只要将bean注入某个地方,Spring就会调用此方法。
import org.springframework.beans.factory.config.BeanDefinition;
...
@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public ExternalUserService externalUserService(UserServiceFactory factory,UserProviderResolver resolver) {
.. create the user service depending on resolver.getProvider()
}
UserServiceFactory用于创建特定服务,具体取决于提供者名称,如您所述。
使用方法getProvider()创建一个类UserProviderResolver,该方法返回当前请求或用户的提供者名称。
您可以在UserProviderResolver中@Autowire HttpRequest来访问当前请求。