开发者

JAXB and Guice: How to integrate and visualize?

开发者 https://www.devze.com 2023-04-06 11:33 出处:网络
I find using JAXB together with Guice possible, but challenging: Both libraries \"fight\" for control over object creation, you have to be careful to avoid cyclic dependencies, and it can get messy wi

I find using JAXB together with Guice possible, but challenging: Both libraries "fight" for control over object creation, you have to be careful to avoid cyclic dependencies, and it can get messy with all the JAXB Adapters and Guice Providers and stuff. My questions are:

  • How do you deal with this configuration? What general strategies / rules of thumb can be applied?
  • Can you point me to a good tutorial or well written sample code?
  • How to visualize the dependencies (including the Adap开发者_开发技巧ters and Providers)?


For some sample code, some example work was done here: http://jersey.576304.n2.nabble.com/Injecting-JAXBContextProvider-Contextprovider-lt-JAXBContext-gt-with-Guice-td5183058.html

At the line that says "Wrong?", put in the recommended line.

I looks like this:

@Provider 
public class JAXBContextResolver implements ContextResolver<JAXBContext> { 

    private JAXBContext context; 
    private Class[] types = { UserBasic.class, UserBasicInformation.class }; 

    public JAXBContextResolver() throws Exception { 
         this.context = 
       new JSONJAXBContext( 
         JSONConfiguration.natural().build(), types); 
     } 

    public JAXBContext getContext(Class<?> objectType) { 
        /* 
        for (Class type : types) { 
            if (type == objectType) { 
                return context; 
            } 
        } // There should be some kind of exception for the wrong type.
        */ 
        return context; 
    } 
} 

//My resource method: 

    @GET 
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 
    public JAXBElement<UserBasic> get(@QueryParam("userName") String userName) { 
        ObjectFactory ob = new ObjectFactory(); 
        UserDTO dto = getUserService().getByUsername(userName); 
        if(dto==null) throw new NotFoundException(); 
        UserBasic ub = new UserBasic(); 
        ub.setId(dto.getId()); 
        ub.setEmailAddress(dto.getEmailAddress()); 
        ub.setName(dto.getName()); 
        ub.setPhoneNumber(dto.getPhoneNumber()); 
        return ob.createUserBasic(ub); 
    } 

//My Guice configuration module: 

public class MyServletModule extends ServletModule { 


    public static Module[] getRequiredModules() { 
        return new Module[] { 
                new MyServletModule(), 
                new ServiceModule(), 
                new CaptchaModule() 
         }; 
    } 


    @Override 
    protected void configureServlets() { 
        bind(UserHttpResource.class); 
        bind(JAXBContextResolver.class);
        serve("/*").with(GuiceContainer.class); 
    } 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号