在 JAX-RS 資源上獲取 Guice 注入

你將需要專案中的 guice-bridge

@ApplicationPath("api")
public class ApiRest extends ResourceConfig {  
    @Inject
    public ApiRest(ServiceLocator serviceLocator, ServletContext servletContext) {
        packages("net.sargue.app.api");

        GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
        GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
        Injector injector = (Injector) servletContext.getAttribute(Injector.class.getName());
        if (injector == null)
            throw new RuntimeException("Guice Injector not found");
        guiceBridge.bridgeGuiceInjector(injector);

        register(RolesAllowedDynamicFeature.class);
    }
}