我是Spring MVC的新手。我一直在寻找解决问题的几天,没有任何成功。
这是我的堆栈:
我的项目结构:
的src
baseproject
存储库
服务
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应用程序,该应用程序使用存储库服务设计模式。部署时出现问题。当第一个Spring存储库由于@Repository注释而被处理时,我得到了以下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
弹簧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");
}
}
最后,我的libs:
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
我知道很多代码,但我想尽可能多地提供详细信息。
谢谢你的帮助。
答案 0 :(得分:9)
我知道这个问题已经超过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();
}
答案 1 :(得分:5)
LocalContainerEntityManagerFactoryBean
的初始化逻辑在afterPropertiesSet()
方法中。通常在设置完所有属性后由Spring调用。如果手动实例化bean,则必须在调用afterPropertiesSet()
之前调用getObject()
。否则,您将获得NullPointerException
。
答案 2 :(得分:2)
尝试
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
...
return localContainerEntityManagerFactoryBean;
}
而不是
@Bean
public EntityManagerFactory entityManagerFactory() {
...
return localContainerEntityManagerFactoryBean.getObject();
}
答案 3 :(得分:0)
@ charleyDc5包含您的应用程序上下文(spring-servlet.xml) &LT; context:component-scan&gt;。是否包含@repository包。有时这可能是造成这个问题的原因。