开发者

Inject DB Instance For Static and Instance Accessibility

I have a POJO that is used with GWT's RequestFactory and an associated proxy. The POJO has both static methods (list()) and instance methods (persist()) which need access to my database. My database connection pool is set up to be injected as a singleton via Guice. What I am unsure of is how exactly can I perform the injection so that both of these types of methods can access it?

Furthermore, the instances of the POJO are created using an empty constructor, thus negating the ability to use constructor injection.

Here's a sample POJO for reference's sake:

public class Person {
    private Integer id;
    private String name;

    public Integer getId() { return this.id; }
    public void setId(Integer id) { this.id = id; }
    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }

    public void persist() {
        //TODO: save state to DB
    }
    public static List<Person> list() {
        //TODO: get all people from DB
        开发者_开发百科return null;
    }
}


Somehow, GWT's style is still not very aware of the needs of dependency injection. This is - to some extent - excusable on the client side, but not so much on the server side (and to be honest, I'd really wish, that the GWT and Guice team will join forces to improve this situation.)

Now, fortunately, Guice provides a "legacy" mechanism for injecting static fields, see "Static injections" in http://code.google.com/docreader/#p=google-guice&s=google-guice&t=Injections). So you can inject your EntityManager/EntityManagerFactory (or whatever you're using to perform persistence) into a static field.

You don't have to do that directly, but you can use a Provider. Then choose the correct scope (e.g. @RequestScoped) to make the provider give you the correct instance.

Note: I haven't tried that yet (though I'm planning to do so), because I'm not yet using RequestFactory in a real project. I hope that the legacy mechanism works in this case, but you may hit some roadblocks (?)


The pojo doesn't have to be default-instantiable if you use a Locator to control how the RequestFactory server code obtains instances of your POJOs by implementing Locator.find() as appropriate for your domain object. Locators also allow you use domain objects that don't conform to the getId() / getVersion() protocol.

@ProxyFor(value = Person.class, locator = PersonLocator.class)
interface PersonProxy extends EntityProxy { .... }

If you need to alter the behavior for most of your domain pojos, you can inject a ServiceLayerDecorator that overloads createDomainObject() and loadDomainObject().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜