目前我这样做的方式是我有一个如下所示的 ApiConfig 类:
public class ApiConfig {
public enum Build{
RELEASE("https://api.endpoint.com"),
STAGE("http://api.stage.endpoint.com"),
DEV("http://api.dev.endpoint.com");
public String endpoint;
Build(String endpoint){
this.endpoint = endpoint;
}
}
}
我有一个接受构建类型的 ApiModule,所以我像这样实例化组件:
ApiComponent component = DaggerApiComponent.builder()
.apiModule(new ApiModule(ApiConfig.Build.DEV))
.build();
因此,现在如果我想更改端点,我将 ApiConfig.Build.DEV 更改为 ApiConfig.Build.STAGE 或 ApiConfig.Build.RELEASE。这是解决这个问题的正确方法吗?最终,我希望能够按一个按钮在三者之间切换。
最佳答案
我就是这样做的:
我有一个基于互联网示例的服务工厂类。请参阅下面的代码。
当我需要创建我的服务实例时,我会调用。
service = ServiceFactory.createRetrofitService(GithubService.class,
GithubService.SERVICE_ENDPOINT);
因此,如果您将 3 个端点添加到 GithubService 接口(interface)。在所需 View 的点击事件中,只需使用所需的 SERVICE_ENDPOINT 调用 ServiceFactory。
例子。
public interface GithubService {
String RELEASE_ENDPOINT = "https://api.endpoint.com";
String STAGE_ENDPOINT = "http://api.stage.endpoint.com";
String DEV_ENDPOINT = "http://api.stage.endpoint.com";
@GET("/users/{login}")
Observable<UserResponse> getUser(@Path("login") String login);
}
在您的 RELEASE 按钮中调用 onClick() :
private GithubService service;
service = ServiceFactory.createRetrofitService(GithubService.class,
GithubService.SERVICE_ENDPOINT);
在您的 STAGE 按钮中调用 onClick() :
private GithubService service;
service = ServiceFactory.createRetrofitService(GithubService.class,
GithubService.STAGE_ENDPOINT);
在您的 DEV 按钮中调用 onClick() :
private GithubService service;
service = ServiceFactory.createRetrofitService(GithubService.class,
GithubService.DEV_ENDPOINT);
服务工厂代码:
public class ServiceFactory {
private static final String TAG = ServiceFactory.class.getSimpleName();
/**
* Creates a retrofit service from an arbitrary class (clazz)
* @param clazz Java interface of the retrofit service
* @param endPoint REST endpoint url
* @return retrofit service with defined endpoint
*/
public static <T> T createRetrofitService(final Class<T> clazz, final String endPoint) {
final RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setLog(new RestAdapter.Log() {
@Override
public void log(String message) {
Log.v(TAG, message);
}
})
.setEndpoint(endPoint)
.build();
T service = restAdapter.create(clazz);
return service;
}
}
关于java - 使用改造和 Dagger 我将如何创建一个可以轻松切换端点的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32237471/