当前位置: 首页 > 面试题库 >

在Spring信息库中注入EntityManager时出现java.lang.NullPointerException

戚研
2023-03-14
问题内容

我是Spring html" target="_blank">MVC的新手。我一直在寻找解决问题的方法,但没有成功。

这是我的堆栈:

  • jBoss 4.2.3GA服务器
    • 我知道这是一个非常旧的版本,但这是我目前仅限于的版本。jBoss 7.1将在接下来的几个月内被批准在我的组织中使用,但是我想让我的R&D应用程序在4.2.3GA服务器上工作。这意味着我已经在/ lib文件夹中添加了所有必需的jar。
  • Spring MVC 4.0.2
  • EJB3.0 / JPA的持久性
  • DBMS是PostgreSQL 9.0.3
  • 我没有使用任何构建/依赖管理工具,例如Maven或Gradle。Gradle正在审批过程中,这是时间的问题。我现在需要自己管理所有依赖项。

我的项目结构:

  • src

    • baseproject

    • model

      • security
      • User.java
      • Role.java
      • …其他与安全相关的实体bean
    • repository

      • security
      • UserRepository.java
      • UserRepositoryImpl.java
      • RoleRepository.java
      • RoleRepositoryImpl.java
      • …其他与安全性相关的存储库

        • 服务
      • SecurityService.java

      • SecurityServiceImpl.java
        • web
      • controller
      • UserController.java(a typical controller)
      • configuration
      • WebConfig.java(the main servlet configuration)
      • PersistenceConfig.java(与持久性有关的所有东西。我认为这是我的问题所在……没有persistence.xml)

PersistenceConfig.java

package baseproject.web.configuration;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class PersistenceConfig {

    @Bean
    public EntityManagerFactory entityManagerFactory() {

        final LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        localContainerEntityManagerFactoryBean.setDataSource(dataSource());
        localContainerEntityManagerFactoryBean.setPackagesToScan("baseproject");

        final Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        props.setProperty("hibernate.hbm2ddl.auto", "validate");
        props.setProperty("hibernate.show_sql", "false");
        props.setProperty("hibernate.validator.apply_to_ddl", "false");
        props.setProperty("hibernate.validator.autoregister_listeners", "false");

        localContainerEntityManagerFactoryBean.setJpaProperties(props);

        return localContainerEntityManagerFactoryBean.getObject();
    }

    @Bean
    public HibernateJpaVendorAdapter jpaVendorAdapter() {

        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();

        hibernateJpaVendorAdapter.setDatabase(Database.POSTGRESQL);
        hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");

        return hibernateJpaVendorAdapter;
    }

    @Bean
    public DataSource dataSource() {

        final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        DataSource dataSource = dsLookup.getDataSource("java:/dsBaseProject");

        return dataSource;
    }

}

UserRepository.java

package baseproject.repository.security;

import java.util.List;

import baseproject.model.security.User;

public interface UserRepository {

    public User findUserByPk(Integer intUserId);
    public List<User> lstUsers(Integer intSortBy);
    public void addUser(User user);
    public void updateUser(User user);
    public void deleteUser(User user);

}

UserRepositoryImpl.java

package baseproject.repository.security;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import baseproject.model.security.User;

@Repository
public class UserRepositoryImpl implements UserRepository {

    @PersistenceContext
    protected EntityManager em;

    public User findUserByPk(Integer intId) {

        User user = null;

        if (intId != null) {
            user = em.find(User.class, intId);
        }

        return user;
    }

public java.util.List<User> lstUsers(Integer intSortBy) {

        List<User> usersList = new ArrayList<User>();

        Query q = em.createNamedQuery("User.lstUsers");

        return usersList;
    }

    public void addUser(User user) {

        user.setIntId(null);
        em.persist(user);
    }

    public void updateUser(User user) {

        User userBd = em.find(User.class, user.getIntId());

        userBd.setStrLastName(user.getStrLastName());
        userBd.setStrFirstName(user.getStrFirstName());
        userBd.setStrUserId(user.getStrUserId());
    }

    public void deleteUser(User user) {

        User userBd = em.find(User.class, user.getIntId());
        em.remove(userBd);
    }
}

SecurityService.java

package baseproject.service;

import java.util.List;

import baseproject.model.security.Method;
import baseproject.model.security.Node;
import baseproject.model.security.Role;
import baseproject.model.security.User;

public interface SecurityService {

    // USERS
    public User findUserByPk(Integer intUserId);
    public User findUserByUserId(String strUserId);

    public void addUser(User user);
    public void updateUser(User user);
    public void deleteUser(User user);

    public List<User> lstUsers(Integer intSortBy);

    public boolean validateUser(User user, String strMethod);

    // ROLES
    public Role findRoleByPk(Integer intRoleId);

    public List<Role> lstRoles(String strLanguage);

    public void addRole(Role role);
    public void updRole(Role role);
    public void delRole(Role role);


    // NODES
    public List<Node> lstParentNodes();


    // METHODS
    public Method findMethodByPk(Integer intMethodId);
    public Method findMethodByName(String strName);
    public List<String> lstUserAllowedMethods(List<Role> lstRolesAllowed, String strLang, String strRemoteUser);
    public List<Method> lstAllMethods();

}

SecurityServiceImpl.java

package baseproject.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import baseproject.model.security.Method;
import baseproject.model.security.Node;
import baseproject.model.security.Role;
import baseproject.model.security.User;
import baseproject.repository.security.MethodRepository;
import baseproject.repository.security.NodeRepository;
import baseproject.repository.security.RoleRepository;
import baseproject.repository.security.UserRepository;

@Service
public class SecurityServiceImpl implements SecurityService {

    UserRepository userRepository;
    RoleRepository roleRepository;
    MethodRepository methodRepository;
    NodeRepository nodeRepository;

    @Override
    @Transactional(readOnly = true)
    public User findUserByPk(Integer intUserId) {
        return userRepository.findUserByPk(intUserId);
    }

    @Override
    @Transactional(readOnly = true)
    public User findUserByUserId(String strUserId) {
        return userRepository.findUserByUserId(strUserId);
    }

    @Override
    @Transactional
    public void addUser(User user) {
        userRepository.addUser(user);
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        userRepository.updateUser(user);
    }

    @Override
    @Transactional
    public void deleteUser(User user) {
        userRepository.deleteUser(user);
    }

    @Override
    @Transactional(readOnly = true)
    public List<User> lstUsers(Integer intSortBy) {
        return null;
    }

    @Override
    @Transactional(readOnly = true)
    public boolean validateUser(User user, String strMethod) {
        return false;
    }

    @Override
    @Transactional(readOnly = true)
    public Role findRoleByPk(Integer intRoleId) {
        return null;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Role> lstRoles(String strLanguage) {
        return roleRepository.lstRoles(strLanguage);
    }

    @Override
    @Transactional
    public void addRole(Role role) {
        roleRepository.addRole(role);
    }

    @Override
    @Transactional
    public void updRole(Role role) {

    }

    @Override
    @Transactional
    public void delRole(Role role) {

    }

    @Override
    @Transactional
    public List<Node> lstParentNodes() {
        return nodeRepository.lstParentNodes();
    }

    @Override
    @Transactional
    public Method findMethodByPk(Integer intMethodId) {
        return methodRepository.findMethodByPk(intMethodId);
    }

    @Override
    @Transactional
    public Method findMethodByName(String strName) {
        return methodRepository.findMethodByName(strName);
    }

    @Override
    @Transactional
    public List<String> lstUserAllowedMethods(List<Role> arlRolesAllowed,
            String strLanguage, String strRemoteUser) {
        return methodRepository.lstUserAllowedMethods(arlRolesAllowed, strLanguage, strRemoteUser);
    }

    @Override
    @Transactional
    public List<Method> lstAllMethods() {
        return methodRepository.lstAllMethods();
    }

}

我的结构基于Springpetclinic应用程序,该应用程序使用存储库服务设计模式。部署时出现问题。由于@Repository批注,在处理第一个Spring存储库时,我得到了正确的以下stacktrace:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepositoryImpl': Injection of persistence dependencies failed; nested exception is java.lang.NullPointerException
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:356)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3856)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4361)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:790)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:770)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:553)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296)
        at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.apache.catalina.core.StandardContext.init(StandardContext.java:5312)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296)
        at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.web.tomcat.service.TomcatDeployer.performDeployInternal(TomcatDeployer.java:301)
        at org.jboss.web.tomcat.service.TomcatDeployer.performDeploy(TomcatDeployer.java:104)
        at org.jboss.web.AbstractWebDeployer.start(AbstractWebDeployer.java:375)
        at org.jboss.web.WebModule.startModule(WebModule.java:83)
        at org.jboss.web.WebModule.startService(WebModule.java:61)
        at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
        at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
        at $Proxy0.start(Unknown Source)
        at org.jboss.system.ServiceController.start(ServiceController.java:417)
        at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
        at $Proxy42.start(Unknown Source)
        at org.jboss.web.AbstractWebContainer.start(AbstractWebContainer.java:466)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
        at org.jboss.mx.interceptor.DynamicInterceptor.invoke(DynamicInterceptor.java:97)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
        at $Proxy43.start(Unknown Source)
        at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
        at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
        at $Proxy9.deploy(Unknown Source)
        at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymentScanner.java:421)
        at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentScanner.java:610)
        at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.doScan(AbstractDeploymentScanner.java:263)
        at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.loop(AbstractDeploymentScanner.java:274)
        at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.run(AbstractDeploymentScanner.java:225)
    Caused by: java.lang.NullPointerException
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.initProxyClassLoader(SharedEntityManagerCreator.java:171)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.<init>(SharedEntityManagerCreator.java:163)
        at org.springframework.orm.jpa.SharedEntityManagerCreator.createSharedEntityManager(SharedEntityManagerCreator.java:135)
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:694)
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:655)
        at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:353)
        ... 99 more

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- Auto-balayage de classes dans le contexte / Auto-scan classes within the context -->
    <context:annotation-config />

</beans>

WebConfig.java

package baseproject.web.configuration;

import java.util.Locale;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "baseproject" })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ResourceBundleMessageSource messageSource() {

        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

        String[] strBaseNames = {
                "resources.messages.layout.LayoutResources",
                "resources.messages.global.GlobalResources",
                "resources.messages.welcome.WelcomeResources",
                "resources.messages.user.UserResources",
                "resources.messages.role.RoleResources",
                "resources.messages.profile.ProfileResources"
        };

        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setBasenames(strBaseNames);

        return messageSource;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor result = new LocaleChangeInterceptor();
        result.setParamName("language");

        return result;
    }

    @Bean
    public LocaleResolver localeResolver() {

        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH);

        return sessionLocaleResolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {

        interceptorRegistry.addInterceptor(localeChangeInterceptor());
    }

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

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/").setViewName("views/welcome/welcomePage");
    }
}

最后,我的库:

aopalliance-1.0.jar
GlobalLibraries.jar
hibernate-core-4.2.8.Final.jar
hibernate-entitymanager-4.2.8.Final.jar
javax.servlet-api-3.0.1.jar
jcifs-1.3.17.jar
jdo-api-3.0.jar
libs.txt
ognl-3.0.6.jar
openjpa-all-2.2.1.jar
slf4j-api-1.6.6.jar
slf4j-log4j12-1.7.5.jar
spring-aop-4.0.2.RELEASE.jar
spring-aspects-4.0.2.RELEASE.jar
spring-beans-4.0.2.RELEASE.jar
spring-context-4.0.2.RELEASE.jar
spring-context-support-4.0.2.RELEASE.jar
spring-core-4.0.2.RELEASE.jar
spring-expression-4.0.2.RELEASE.jar
spring-framework-bom-4.0.2.RELEASE.jar
spring-instrument-4.0.2.RELEASE.jar
spring-jdbc-4.0.2.RELEASE.jar
spring-jms-4.0.2.RELEASE.jar
spring-ldap-core-2.0.1.RELEASE.jar
spring-ldap-core-tiger-2.0.1.RELEASE.jar
spring-messaging-4.0.2.RELEASE.jar
spring-orm-4.0.2.RELEASE.jar
spring-oxm-4.0.2.RELEASE.jar
spring-security-config-3.2.2.RELEASE.jar
spring-security-core-3.2.2.RELEASE.jar
spring-security-ldap-3.2.3.RELEASE.jar
spring-security-web-3.2.2.RELEASE.jar
spring-test-4.0.2.RELEASE.jar
spring-tx-4.0.2.RELEASE.jar
spring-web-4.0.2.RELEASE.jar
spring-webmvc-4.0.2.RELEASE.jar
spring-webmvc-portlet-4.0.2.RELEASE.jar
spring-websocket-4.0.2.RELEASE.jar
thymeleaf-2.1.2.RELEASE.jar
thymeleaf-spring4-2.1.2.RELEASE.jar

I know that’s a lot of code but I wanted to provide as much details as
possible.

THANK YOU for help.


问题答案:

I know this question is over 9 month old, but I stumbled over the same problem
and managed to fix it. The solution from Andrei Stefan is one step in the
right direction. Surprisingly, when you call getObject() within the method to
retrieve the entityManagerFactory, it will throw a NPE, but if you call the
exact same method outside of the entityManagerFactory method it will work.

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory().getObject());
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dataSource());

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);
        jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");

        factory.setJpaVendorAdapter(jpaVendorAdapter);
        return factory;
    }

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
    }


 类似资料:
  • 如何使用Spring JPA注入EntityManager对象 我使用的是spring上下文 我的dao是,注入EntityManager 我的persistence.xml 所以我收到以下错误:

  • 在我的J2EE应用程序中,我尝试使用spring boot和JPA技术,并将EntityManager注入DAO层。然而,我有一些问题。。。我的用户CRUD存储库: 我的spring boot应用程序类: } 最后是我的坚持。xml,位于src/main/resources/META-INF文件夹中: 所以,当我尝试使用这个注入的entityManager时,我得到了NullPointerExce

  • 问题内容: 专家/大师/朋友 我们正在使用Spring 3.2,JPA 2,Hibernate 4.2组合,并在尝试将任何带弹簧注释的bean注入实现的EmtyInterceptor时,遇到了这个奇怪的null指针问题,如下所示。我们已经尝试给这个豆子和一个春天豆子添加注释,但是没有运气。 非常感谢您为解决这个难题提供的任何帮助。 在应用程序的其他任何地方,注入都像没有任何问题的魅力一样。这是我们

  • 专家/大师/朋友 我们正在使用Spring 3.2、JPA 2、Hibernate 4.2组合,并面临这个奇怪的空指针问题,同时试图将任何Spring注释的bean注入到EmtyInterceptor中,实现如下所示。我们试着给这个豆子和Spring的豆子注释,但是没有成功。 非常感谢您对解决这个难题的任何帮助。 在应用程序的其他地方,注入就像一个魅力,没有任何问题。这是我们的应用程序上下文。xm

  • 我尝试了,,和组合,但没有任何效果@注入失败maven quarkus插件构建: [错误]原因:javax。企业注射UnsatisfiedSolutionException:javax类型的未满足依赖关系。坚持不懈EntityManager和限定符[@Default] 我尝试了使用和不使用persistence.xml.我的数据源和application.properties工作正常,因为我可以注