Google Guice桌面应用程序 - 如何使其工作?

Pau*_*aul 4 java inject guice

我在我的网络应用程序中使用Guice没有问题,我想在桌面应用程序中使用它.我当然缺少一件事 - 某种方式告诉我的应用程序如何绑定所有内容并知道什么是什么.在Web应用程序中,我在Application类中声明了这一点,我应该如何在桌面应用程序中执行此操作?

这是我正在使用的相关代码:

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);
 }
Run Code Online (Sandbox Code Playgroud)

我的主要课程:

@Inject
public Repository<Project> projectRepo;

public void createNewProject() {
   ...
   projectRepo.persist(newProject);
}
Run Code Online (Sandbox Code Playgroud)

我当然正在使用projectRepo.persist(newProject);

那么,我还需要做些什么才能让它发挥作用?

编辑:

好的,那个部分现在正常工作,谢谢:)似乎我需要做更多的事情来让持久性工作那样.

我现在在这里接受NPE:

public void persist(T entity) 
{ 
pmProvider.get().makePersistent(entity); 
} 
Run Code Online (Sandbox Code Playgroud)

get()在这里返回null

它看起来像install(new PersistenceManagerFilter.GuiceModule()); 是不足够的.我需要做什么?我的Repository类以以下内容开头:

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; 
} 
Run Code Online (Sandbox Code Playgroud)

在我的PMF,我有:

public static class GuiceModule extends AbstractModule { 

  @Override protected void configure() { 
    bind(PersistenceManager.class).toProvider(new Provider<PersistenceManager>() {
      public PersistenceManager get() { 
         return PersistenceManagerFilter.pm.get(); 
         } 
      }); 
    } 
   }
Run Code Online (Sandbox Code Playgroud)

Mai*_*kov 5

Bootstrap使用main方法创建类.

将当前的静态主方法代码移动到非静态方法代码.例如Application#run.

Bootstrap类中创建main方法:

public static void main(String[] args) {
    Injector injector = Guice.createInjector(new GuiceModule())
    Application app = injector.getInstance(Application.class);
    app.run();
}
Run Code Online (Sandbox Code Playgroud)

运行Bootstrap类.