0
@Component
@Qualifier("SUCCESS")
public class RandomServiceSuccess implements RandomService{
    public String doStuff(){
       return "success";
   }
}

@Component
@Qualifier("ERROR")
public class RandomServiceError implements RandomService{
    public String doStuff(){
       throw new Exception();
   }
}

调用代码

 @Controller
    public class RandomConroller {
        @Autowired 
        private RandomService service;
        public String do(){
           service.doStuff();
       }
    }

我需要在这里做的是让它们根据可以从 http 请求的一些自定义 http 标头中检索的值进行交换。谢谢!

4

3 回答 3

3

我完全同意 Sotirios Delimanolis 的观点,即您需要注入所有实现并在运行时选择其中之一。

如果您有许多实现RandomService并且不想RandomController与选择逻辑混乱,那么您可以让RandomService实现负责选择,如下所示:

public interface RandomService{
    public boolean supports(String headerValue);
    public String doStuff();
}

@Controller
public class RandomConroller {
    @Autowired List<RandomService> services;

    public String do(@RequestHeader("someHeader") String headerValue){
        for (RandomService service: services) {
            if (service.supports(headerValue)) {
                 return service.doStuff();
            }
        }
        throw new IllegalArgumentException("No suitable implementation");
    }
}

如果您想为不同的实现定义优先级,您可以使用Ordered注入的实现并将其放入TreeSetwith 中OrderComparator

于 2013-10-29T17:55:07.130 回答
0

您可以同时注入两者并使用您需要的那个。

@Inject
private RandomServiceSuccess success;

@Inject
private RandomServiceError error;

...
String value = request.getHeader("some header");
if (value == null || !value.equals("expected")) {
    error.doStuff();
} else {
    success.doStuff();
}
于 2013-10-29T17:36:44.477 回答
0

在为每个实例指定不同的 ID 后,应使用限定符指定要在字段中注入的接口实例。按照@Soritios 的建议,您可以执行以下操作:

@Component("SUCCESS")
public class RandomServiceSuccess implements RandomService{
    public String doStuff(){
       return "success";
   }
}

@Component("ERROR")
public class RandomServiceError implements RandomService{
    public String doStuff(){
       throw new Exception();
   }
}


@Component
public class MyBean{
    @Autowired
    @Qualifier("SUCCESS")
    private RandomService successService;

    @Autowired
    @Qualifier("ERROR")
    private RandomService successService;

    ....
    if(...)
}

...或者您可以根据您的参数从应用程序上下文中获取您想要的实例:

@Controller
public class RandomConroller {
    @Autowired
    private ApplicationContext applicationContext;

    public String do(){
        String myService = decideWhatSericeToInvokeBasedOnHttpParameter();

        // at this point myService should be either "ERROR" or "SUCCESS"
        RandomService myService = applicationContext.getBean(myService);

        service.doStuff();
   }
}
于 2013-10-29T17:46:34.927 回答