所有的类都是从同一个接口实现的。根据我们接收的输入值,创建bean的最佳方法是什么。
如果输入值是a,需要调用一个类,如果输入值是b,则调用不同的类。
你云尝试这样的东西。
@Component
public class SomeServiceFactory {
@Autowired
private Someservice someserviceA;
@Autowired
private Someservice someserviceB;
@Autowired
private MyServiceThree SomeserviceC;
public SomeService getSomeService(String serviceType) {
if (serviceType.equals("A")) {
return someserviceA;
} else if (serviceType.equals("B")) {
return someserviceB;
} else {
return someserviceC;
}
}
}
public interface MyService {
void doSomething();
}
@Service
public class MyServiceA implements MyService {
@Override
public void doSomething() {
// do your business A
}
}
@Service
public class MyServiceB implements MyService {
@Override
public void doSomething() {
// do your business B
}
}
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MyServiceContext {
private final Map<String, MyService> strategyMap;
public MyService getMyService(String key) {
// the key is the bean name
return strategyMap.get(key);
}
}
@Autowired
private MyServiceContext context;
...
// your input key must be the bean name.
context.getMyService(yourInputValue).doSmething();