Skip to content

Instantly share code, notes, and snippets.

@luiswolff
Created February 18, 2019 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luiswolff/4c8827253a60e27e1132c60ceb40b035 to your computer and use it in GitHub Desktop.
Save luiswolff/4c8827253a60e27e1132c60ceb40b035 to your computer and use it in GitHub Desktop.
package de.wolff.dsi;
public interface DynamicService {
String invoke();
}
package de.wolff.dsi;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("api")
public class DynamicServiceInvokationApp extends Application {
}
package de.wolff.dsi;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
public @interface DynamicServiceType {
String value();
}
package de.wolff.dsi;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("services")
@ApplicationScoped
public class Endpoint {
@Inject
@Any // This is importent because we want a reference to all implementations
private Instance<DynamicService> services;
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonObject invokeService(@QueryParam("serviceName") String serviceName) {
DynamicServiceType serviceType = new DynamicServiceTypeLiteral(serviceName);
DynamicService service = services.select(serviceType).get();
return Json.createObjectBuilder().add("result", service.invoke()).build();
}
private class DynamicServiceTypeLiteral extends AnnotationLiteral<DynamicServiceType> implements DynamicServiceType {
private static final long serialVersionUID = 6319075567055671586L;
private final String serviceName;
public DynamicServiceTypeLiteral(String serviceName) {
this.serviceName = serviceName;
}
@Override
public String value() {
return serviceName;
}
}
}
package de.wolff.dsi;
import javax.enterprise.context.Dependent;
@DynamicServiceType("first")
@Dependent
public class FirstDynamicServiceImpl implements DynamicService{
@Override
public String invoke() {
return "Response first service";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment