users@jersey.java.net

Re: Guice provider

From: Marc Hadley <Marc.Hadley_at_Sun.COM>
Date: Fri, 16 Nov 2007 14:13:49 -0500

Great ! Let me know if there's a blog entry describing your work I can
link to.

Thanks,
Marc.

On Nov 16, 2007, at 11:50 AM, Christian wrote:

> Hi jersey users,
>
> Just to let you know, copying Mark hadley's note on spring's jersey
> integration (
> http://weblogs.java.net/blog/mhadley/archive/2007/09/integrating_jer.html)
> ,
> I have been able to instantiate ressources services using the guice
> framework
> (http://code.google.com/p/google-guice/)
>
> Works like a charm so far.
>
>
>
> import com.sun.ws.rest.spi.resource.ResourceFactory;
>> import java.lang.annotation.Documented ;
>> import java.lang.annotation.ElementType;
>> import java.lang.annotation.Retention;
>> import java.lang.annotation.RetentionPolicy;
>> import java.lang.annotation.Target;
>>
>>
>> @Target({ElementType.TYPE})
>> @Retention( RetentionPolicy.RUNTIME)
>> @Documented
>> @ResourceFactory(GuiceProvider.class)
>>
>>> public @interface GuiceFactory {}
>>
>>
>
>
>
> public class GuiceProvider implements ResourceProvider {
>
> private Class<?> resourceClass=null;
> private static Injector guiceInjector=null;
>
>
> protected static synchronized void
> initGuiceInjector(ResourceProviderContext context) {
> if (guiceInjector==null) {
> DummyResource r=new DummyResource();
> context.injectDependencies(r);
> guiceInjector=Guice.createInjector(new NaiadeModule(
> r.servletConfig));
> }
> }
>
> public void init(Class<?> resourceClass, Map<String, Boolean> arg1,
> Map<String, Object> arg2) {
> this.resourceClass = resourceClass;
> }
>
> public Object getInstance(ResourceProviderContext context) throws
> ContainerException {
> initGuiceInjector(context);
> Object resource=null;
> try {
> resource=this.resourceClass.newInstance();
> } catch (InstantiationException ex) {
> throw new ContainerException("Unable to create resource",
> ex);
> }
> catch (IllegalAccessException ex) {
> throw new ContainerException("Unable to create resource",
> ex);
> }
> context.injectDependencies(resource);
> guiceInjector.injectMembers(resource);
> return resource;
> }
>
>
> public static class DummyResource {
> @Resource
> public ServletConfig servletConfig;
> }
>
> }

---
Marc Hadley <marc.hadley at sun.com>
CTO Office, Sun Microsystems.