Tomcat中的EntityManager注入

时间:2015-08-03 21:03:08

标签: java spring hibernate spring-mvc tomcat

我正在尝试使用Spring MVC 4,Hibernate和JPA编写将在Tomcat 8上运行的Web应用程序。

我正在进行此注释驱动,因此如果我能帮助它,那么Spring代码中没有XML。

我在应用程序中有几个层:作为Spring MVC Web应用程序一部分的控制器;服务和存储库(虽然它们没有注释为Spring服务等),但它们都存在于Web应用程序的WAR中分发的不同JAR文件中。

我想在我的代码中注入EntityManager或EntityManagerFactory(我使用了存储库模式的变体),但无法使其工作。

我还定义了一个persistence.xml来设置持久性单元。

我已经尝试了几件事,但没有任何作用。

我已将@PersistenceContext添加到EntityManager和EntityManagerFactory变量中;

我在存储库代码中尝试了@PersistenceUnit,但没有运气。

我尝试的最后一件事(在此帖Injecting EntityManager with a producer in tomcat之后)是在Web应用程序中添加一个监听器并在我的代码中使用@Inject。创建了监听器,但是' createEntityManager'方法永远不会被调用(是的,我已经改变了它来添加@Produces注释)

所以我的听众看起来像这样:

 @Produces
public EntityManager createEntityManager() {
    System.out.println("*********** EntityManagerFactoryListener - createEntityManager: "); 
    if (entityManagerFactory == null) {
        throw new IllegalStateException("Context is not initialized yet.");
    }

    return entityManagerFactory.createEntityManager();
}

我的reoository看起来像这样

    @Inject
public void setEntityManager(final EntityManager entityManager) {
    this.entityManager = entityManager;
    System.out.println("*********** entityManager: " + entityManager); 
}

我得到的错误是

    Error creating bean with name 'hibernateRepository': Injection of autowired dependencies failed
    ...

    nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] ...

我错过了什么吗?我甚至可以在Tomcat中执行此操作,还是需要EJB容器?

修改

在回答问题时,我有一个WebApplictionInitializer,如下所示:

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
      WebApplicationContext context = getContext();
      servletContext.addListener(new ContextLoaderListener(context));
      ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context) );
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/");
  }

  private WebApplicationContext getContext() {
      AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
      context.register(WebConfig.class);
      return context;
  }

和WebMvcConfigurerAdapter看起来像:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.pluralsight")
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
  }

  @Bean
  public InternalResourceViewResolver  getInternalResourceViewResolver() {
      InternalResourceViewResolver resolver = new InternalResourceViewResolver();
      resolver.setPrefix("/WEB-INF/jsp/");
      resolver.setSuffix(".jsp");

      return resolver;
  }
}

0 个答案:

没有答案