如何根据输入的不同创建不同的春豆?

问题描述 投票:0回答:1

所有的类都是从同一个接口实现的。根据我们接收的输入值,创建bean的最佳方法是什么。

如果输入值是a,需要调用一个类,如果输入值是b,则调用不同的类。

java spring
1个回答
0
投票

你云尝试这样的东西。

    @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;
        } 
}
}

0
投票
  1. 首先是接口
public interface MyService {
    void doSomething();
}
  1. 然后定义两个实现。
@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
    }
}

  1. 上下文。
@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);
    }
}
  1. 使用方法
@Autowired
private MyServiceContext context;
...
// your input key must be the bean name.
context.getMyService(yourInputValue).doSmething();
© www.soinside.com 2019 - 2024. All rights reserved.