动态选择依赖关系 [英] Dynamically choose dependency without if else

查看:86
本文介绍了动态选择依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在没有其他条件的情况下选择依赖项。

How can i choose dependency without if else condition.

假设我有一个接口:

public interface A{

String doSomething(String req);
}

有两个服务工具 A

@Component
public class FirstImpl implements A{

   @override
   String doSomething(String req){
   return "something";
  }
}

和:

@Component
public class SecondImpl implements A{

 @override
    String doSomething(String req){
    return "something";
  }
}

现在,我创建一个AdapterService类:

Now i create a AdapterService class:

@Component
public class AdapterService{
    @Autowired
    private FirstImpl first;
    @Autowired
    private SecondImpl second;

    public getService(String name){
        if("name".equals("First")){
            return first;
        }else if("name".equals("Second")){
            return second;
        }
    }
}

现在调用实现:

@Service
public class BusinessService{
    @Autowired
    private AdapterService adapterService;

    void doSomething(String name,String req){
        return adapterService.getService(name).doSomething();
    }
}

现在,如果我需要创建另一个实现A的类然后需要在ServiceAdapter类中添加条件。像 Third .equals(name)返回另一个注入的服务。对于每个新服务,需要添加其他条件,然后注入相应的服务。我如何避免这种Adapter类。 Spring从名称中动态选择依赖关系。

Now if i need to create another class which implements A then need to add condition in ServiceAdapter class. Like "Third".equals(name) return another injected service. For every new service there need to add another if else condition and inject corresponding service. How can i avoid this Adapter class. Spring dynamically choose depenedency from name.

推荐答案

如果可以访问 applicationContext 对象,您可以调用

If you have access to applicationContext object, you can call


applicationContext.getBean(name)

applicationContext.getBean(name)

并完全避免使用ServiceAdapter类。唯一的事情就是您需要将那些豆放入容器中。

and totally avoid the ServiceAdapter class. Only thing is you need to have those beans in the container.

尝试以下操作:

@Component
public class AdapterService{
    @Autowired
    private ApplicationContext applicationContext;

    public A getService(String name){
        return applicationContext.getBean(name,A.class);
    }
}

这篇关于动态选择依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆