在 Spring 存储库中注入 EntityManager 时出现 java.lang.NullPointerException
Posted
技术标签:
【中文标题】在 Spring 存储库中注入 EntityManager 时出现 java.lang.NullPointerException【英文标题】:java.lang.NullPointerException upon EntityManager injection in Spring repository 【发布时间】:2014-06-27 05:26:40 【问题描述】:我是 Spring MVC 的新手。几天来我一直在寻找解决问题的方法,但没有成功。
这是我的堆栈:
jBoss 4.2.3GA 服务器 我知道这是一个非常旧的版本,但我现在仅限于此。 jBoss 7.1 将在未来几个月内获准在我的组织中使用,但我想让我的研发应用程序在 4.2.3GA 服务器上工作。这意味着我已在 /lib 文件夹中添加了所有必需的 jar。 Spring MVC 4.0.2 EJB3.0 / JPA 用于持久性 DBMS 是 PostgreSQL 9.0.3 我没有使用任何构建/依赖管理工具,例如 Maven 或 Gradle。 Gradle 正在审批过程中,所以这只是时间问题。我现在需要自己管理所有依赖项。我的项目结构:
src
基础项目
型号 安全 User.java Role.java ...其他与安全相关的实体 bean存储库
安全 UserRepository.java UserRepositoryImpl.java RoleRepository.java RoleRepositoryImpl.java ...其他与安全相关的存储库服务
SecurityService.java SecurityServiceImpl.java 网络 控制器 UserController.java(典型的控制器) 配置 WebConfig.java(主 servlet 配置) 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();
我的结构基于 Spring petclinic 应用程序,该应用程序使用存储库服务设计模式。部署时出现问题。由于 @Repository 注释,当第一个 Spring 存储库被处理时,我得到了以下堆栈跟踪:
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
我知道代码很多,但我想提供尽可能多的细节。
感谢您的帮助。
【问题讨论】:
【参考方案1】:我知道这个问题已经超过 9 个月了,但我偶然发现了同样的问题并设法解决了它。 Andrei Stefan 的解决方案是朝着正确方向迈出的一步。令人惊讶的是,当您在方法中调用 getObject() 来检索 entityManagerFactory 时,它会抛出 NPE,但如果您在 entityManagerFactory 方法之外调用完全相同的方法,它将起作用。
@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();
【讨论】:
【参考方案2】:LocalContainerEntityManagerFactoryBean
的初始化逻辑在afterPropertiesSet()
方法中。通常在设置完所有属性后由 Spring 调用它。如果手动实例化 bean,则必须在调用 getObject()
之前调用 afterPropertiesSet()
。否则你会得到一个NullPointerException
。
【讨论】:
【参考方案3】:试试
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
...
return localContainerEntityManagerFactoryBean;
而不是
@Bean
public EntityManagerFactory entityManagerFactory()
...
return localContainerEntityManagerFactoryBean.getObject();
【讨论】:
现在我又遇到了一个错误。 org.springframework.beans.factory.BeanCreationException:在类路径资源[baseproject/web/configuration/PersistenceConfig.class]中定义名称为“entityManagerFactory”的bean创建错误:调用init方法失败;嵌套异常是 java.lang.NoClassDefFoundError: org/jboss/logging/BasicLogger。看来容器还想管理实体管理器…… 根据this post和this one,你需要jboss-logging.jar
,因为Hibernate需要它。
添加了 jboss-logging-3.1.0.GA.jar 和 hibernate-commons-annotations-4.0.2.Final.jar (因为我添加了 jboss-logging.jar 后它丢失了)。还是一样的 NPE。
您的UserRepositoryImpl
没有实现UserRepository
接口的任何原因?
我的错误。我忘了在这里写,但真正的来源是正确的。在主要问题中编辑。【参考方案4】:
@charleyDc5 你的应用程序上下文(spring-servlet.xml)是否包括 。 @repository 包是否包含在其中。有时这可能是导致此问题的原因。
【讨论】:
查看我的编辑。我添加了 spring-servlet.xml 和 WebConfig.java。如您所见,我尽可能使用注释。 检查此链接这可能会有所帮助***.com/questions/7414794/… 查看我的 WebConfig 文件。我将 @ComponentScan 注释设置为 baseproject 包。存储库位于“baseproject.repository”中。我猜组件扫描默认循环遍历所有子包?根据我在您之前提供的链接上阅读的内容,答案是肯定的。以上是关于在 Spring 存储库中注入 EntityManager 时出现 java.lang.NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章
Spring @transactional 在存储库中不起作用
如何在 jpa spring 存储库中使用 OrderBy?
在 Spring MongoDB 存储库中使用 $slice 和 @Query