I have used Guice in my web app without problems and I wanted to use it in desktop app. I am certainly missing one thing - some way to tell my app how to bind everything and know what is what. In web app, I had declaration for that in Application class, how should I do it in my desktop app?
Here is relevant code that I am using:
public class GuiceModule extends AbstractModule
{
@Override
protected void configure()
{
// Enable per-request-thread PersistenceManager injection.
install(new PersistenceManagerFilter.GuiceModule());
// Business object bindings go here.
bind(ProjectQueries.class).to(JdoProjectQueries.class);
bind(new TypeLiteral<Repository<Project>>() { }).to(JdoProjectRepository.class);
}
My main class:
@Inject
public Repository<Project> projectRepo;
public void createNewProject() {
...
projectRepo.persist(newProject);
}
I am of course getting on projectRepo.persist(newProject);
So, what else do I have to do to make it work?
EDIT:
Ok, that part work now, thanks :) It seems that I need to do a bit more though to make persistence work that way.
I am getting NPE here now:
public void persist(T entity)
{
pmProvider.get().makePersistent(entity);
}
get() returns null here
It looks like install(new PersistenceManagerFilter.GuiceModule()); is not enough. What do I need to do? My Repository class starts with:
public abstract class JdoRepository<T> implements Repository<T> {
private final Class<T> clazz;
private final Provider<PersistenceManager> pmProvider;
protected JdoRepository(Class<T> clazz, Provider<PersistenceManager> pmProvider) { this.clazz = clazz; this.pmProvider = pmProvider;
}
At my PMF I have:
public static class GuiceModule extends AbstractModule {
@Override protected void configure() {
bind(PersistenceManager.class).toProvider(new Provider<PersistenceManager>() {
public PersistenceManager get() {
return PersistenceManagerFilter.pm.get();
}
});
}
}
Create Bootstrap
class with main method.
Move your current static main method code to non-static one. For example Application#run
.
Create main method in Bootstrap
class:
public static void main(String[] args) {
Injector injector = Guice.createInjector(new GuiceModule())
Application app = injector.getInstance(Application.class);
app.run();
}
Run Bootstrap
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With