4

I am new to Spring MVC. I've been searching for few days for a solution to my problem, without any success.

Here is my stack:

  • jBoss 4.2.3GA server
    • I know it's a very old version, but that is what I am limited to right now. jBoss 7.1 will be approved for use in my organization within the next few months, but I would like to make my R&D application work in the 4.2.3GA server. That means I have added all required jars in my /lib folder.
  • Spring MVC 4.0.2
  • EJB3.0 / JPA for persistence
  • DBMS is PostgreSQL 9.0.3
  • I am not using any build/dependency management tool such like Maven or Gradle. Gradle is in approval process so it's a matter of time. I need to manage all dependencies myself for now.

My project structure:

  • src

    • baseproject

      • model
        • security
          • User.java
          • Role.java
          • ... other security related entity beans
      • repository

        • security
          • UserRepository.java
          • UserRepositoryImpl.java
          • RoleRepository.java
          • RoleRepositoryImpl.java
          • ... other security related repositories
      • service

        • SecurityService.java
        • SecurityServiceImpl.java
      • web
        • controller
          • UserController.java (a typical controller)
        • configuration
          • WebConfig.java (the main servlet configuration)
          • PersistenceConfig.java (everything related to persistence. I think this is where my problem is... no 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();
    }

}

I have based my structure on the Spring petclinic application, which uses the repository-service design pattern. The problem is occuring upon deployment. I got the following stacktrace right when the first Spring repository is getting processed because of the @Repository annotation:

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");
    }
}

Finally, my 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

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

THANK YOU for help.

Charles Morin
  • 1,449
  • 4
  • 32
  • 50

4 Answers4

9

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();
    }
AdminAffe
  • 126
  • 1
  • 8
5

The initialization logic of LocalContainerEntityManagerFactoryBean is in the afterPropertiesSet() method. Usually it is called by Spring after all properties have been set. You have to call afterPropertiesSet() before calling getObject() if you manually instantiate the bean. Otherwise you'll get a NullPointerException.

Christoph Leiter
  • 9,147
  • 4
  • 29
  • 37
2

Try

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    ...
    return localContainerEntityManagerFactoryBean;
}

instead of

@Bean
public EntityManagerFactory entityManagerFactory() {
    ...
    return localContainerEntityManagerFactoryBean.getObject();
}
Andrei Stefan
  • 51,654
  • 6
  • 98
  • 89
  • Now I got another error. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [baseproject/web/configuration/PersistenceConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/jboss/logging/BasicLogger. It looks like the container still wants to manage the entity manager... – Charles Morin May 09 '14 at 14:07
  • According to [this post](http://stackoverflow.com/questions/15022438/hibernate-configuration-troubles) and [this one](http://stackoverflow.com/questions/11639997/how-do-you-configure-logging-in-hibernate-4), you need `jboss-logging.jar`, as Hibernate requires it. – Andrei Stefan May 09 '14 at 14:14
  • Added jboss-logging-3.1.0.GA.jar and hibernate-commons-annotations-4.0.2.Final.jar (as it was missing after I had added jboss-logging.jar). Still the same NPE. – Charles Morin May 09 '14 at 14:56
  • Any reason why your `UserRepositoryImpl` doesn't implement `UserRepository` interface? – Andrei Stefan May 09 '14 at 15:47
  • My mistake. I had forgot to write here but the real source is correct. Edited in the main question. – Charles Morin May 09 '14 at 17:05
  • @AndreiStefan your solution didn't work for me as I get another error which indicated Spring can't inject some ``Set`` of ``EntityManager`` (can't recall the exact exception's message) but I did call the ``afterPropertiesSet()`` method before calling the ``getObject()``. – maxxyme Dec 13 '16 at 11:27
0

@charleyDc5 does your application context (spring-servlet.xml) includes < context:component-scan >. Is the @repository package included in it. some times this might be a cause for this issue.

Tim
  • 1,321
  • 1
  • 22
  • 47
  • see my edit. I have added spring-servlet.xml and WebConfig.java. As you can see, I use annotations all the time when possible. – Charles Morin May 09 '14 at 13:31
  • check this link this might help http://stackoverflow.com/questions/7414794/difference-between-contextannotation-config-vs-contextcomponent-scan – Tim May 09 '14 at 13:39
  • See my WebConfig file. I got the @ComponentScan annotation set to the baseproject package. Repositories are located in "baseproject.repository". I guess the component scan loops through all subpackages by default? Answer is yes based on what I read on the link you provided earlier. – Charles Morin May 09 '14 at 14:06