Andrea Grimandi
Andrea Grimandi

Reputation: 641

Spring + Hibernate: Error bean creation

I'm developing a Spring MVC + Hibernate web application and I'm stuck with this exception:

Dec 07, 2015 11:52:51 AM org.springframework.web.context.ContextLoader 

initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainRestController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.grimi.babel.service.LoginService it.grimi.babel.controller.MainRestController.loginService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.grimi.babel.service.dao.LoginDao it.grimi.babel.service.LoginServiceImpl.loginDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in file [C:\NSI\_progetti\EclipseWorkspace\BabelIface\target\BabelIface\WEB-INF\classes\it\grimi\babel\service\dao\LoginDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.grimi.babel.service.dao.LoginDaoImpl]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5014)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:677)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:552)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1717)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1516)
    at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:912)
    at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:371)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:614)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2476)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2465)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.grimi.babel.service.LoginService it.grimi.babel.controller.MainRestController.loginService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.grimi.babel.service.dao.LoginDao it.grimi.babel.service.LoginServiceImpl.loginDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in file [C:\NSI\_progetti\EclipseWorkspace\BabelIface\target\BabelIface\WEB-INF\classes\it\grimi\babel\service\dao\LoginDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.grimi.babel.service.dao.LoginDaoImpl]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:571)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 58 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.grimi.babel.service.dao.LoginDao it.grimi.babel.service.LoginServiceImpl.loginDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in file [C:\NSI\_progetti\EclipseWorkspace\BabelIface\target\BabelIface\WEB-INF\classes\it\grimi\babel\service\dao\LoginDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.grimi.babel.service.dao.LoginDaoImpl]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1145)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1069)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:543)
    ... 60 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.grimi.babel.service.dao.LoginDao it.grimi.babel.service.LoginServiceImpl.loginDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in file [C:\NSI\_progetti\EclipseWorkspace\BabelIface\target\BabelIface\WEB-INF\classes\it\grimi\babel\service\dao\LoginDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.grimi.babel.service.dao.LoginDaoImpl]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:571)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 71 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in file [C:\NSI\_progetti\EclipseWorkspace\BabelIface\target\BabelIface\WEB-INF\classes\it\grimi\babel\service\dao\LoginDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.grimi.babel.service.dao.LoginDaoImpl]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1105)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1145)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1069)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:543)
    ... 73 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [it.grimi.babel.service.dao.LoginDaoImpl]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1098)
    ... 84 more
Caused by: java.lang.ExceptionInInitializerError
    at it.grimi.babel.hibernate.utils.SingleSessionFactory.getInstance(SingleSessionFactory.java:42)
    at it.grimi.babel.service.dao.LoginDaoImpl.<init>(LoginDaoImpl.java:20)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
    ... 86 more
Caused by: org.hibernate.MappingNotFoundException: resource: it/grimi/babel/model/Login.hbm.xml not found
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:746)
    at org.hibernate.cfg.Configuration.addClass(Configuration.java:791)
    at it.grimi.babel.hibernate.utils.SingleSessionFactory$SingleSessionHelper.getSingleSession(SingleSessionFactory.java:25)
    at it.grimi.babel.hibernate.utils.SingleSessionFactory$SingleSessionHelper.<clinit>(SingleSessionFactory.java:13)
    ... 93 more

Dec 07, 2015 11:52:51 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: One or more listeners failed to start. Full details will be found in the appropriate container log file
Dec 07, 2015 11:52:51 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/BabelIface] startup failed due to previous errors
Dec 07, 2015 11:52:51 AM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deployment of configuration descriptor C:\NSI\_software\apache-tomcat-7.0.62\conf\Catalina\localhost\BabelIface.xml has finished in 1,790 ms

My apologies the prolixity... but the exception itself is longer and this extract should (I guess) be the most important part of it.

I know it's something wrong with the LoginDao declaration in LoginDaoImpl (isn't it?) but I can't figure what (Actually It's also pretty hard for me to understand it due to my early skills with Spring, so, I need some help)

I've followed this example trying to change something due to my project requirements. It was clearly a well done example indeed my application basically has the same structure but it has also the SingleSessionFactory class (shown below) wrapping all configurations to make Hibernate talk to the database (because xml makes me sick).

Right, so... here the famous class:

 public class SingleSessionFactory {

    private SingleSessionFactory() {
    }

    private static class SingleSessionHelper {

        private static final SessionFactory SESSION_FACTORY = getSingleSession();

        private static SessionFactory getSingleSession() {

            if (SESSION_FACTORY == null) {
                Configuration hConf = new Configuration();

                hConf.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
                hConf.setProperty("hibernate.connection.datasource", "jdbc:postgresql://127.0.0.1:5432/postgres");
                hConf.setProperty("hibernate.connection.username", "postgres");
                hConf.setProperty("hibernate.connection.password", "ziocamper");

                hConf.addClass(it.grimi.babel.model.Login.class);
                hConf.addClass(it.grimi.babel.model.User.class);

                try {
                    return hConf.buildSessionFactory();
                } catch (Throwable ex) {
                    System.out.println(ex.getMessage());
                    throw new ExceptionInInitializerError(ex);
                }
            }
            return SESSION_FACTORY;
        }
    }

    public static SessionFactory getInstance() {
        return SingleSessionHelper.SESSION_FACTORY;
    }

}

...and I wish to post either LoginDaoImpl, LoginServiceImpl classes and the MainRestController class as a entry point of my REST APIs.

LoginDaoImpl

    @Repository("loginDao")
public class LoginDaoImpl implements LoginDao {

    private SessionFactory sessionFactory = SingleSessionFactory.getInstance();

    public User doLogin(User user) {
        return (User) this.sessionFactory.getCurrentSession().createQuery("from users where username = :username and password =: password ")
                .setParameter("username", user.getUsername())
                .setParameter("password", user.getPassword()).list().get(0);
    }

}

LoginServiceImpl

    @Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Autowired
    LoginDao loginDao;

    public User doLogin(User user) {
        return loginDao.doLogin(user);
    }

}

MainRestController

    @RestController
public class MainRestController {

    @Autowired
    LoginService loginService;

    @RequestMapping(
            value = "/login",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public ResponseEntity<User> doLogin(@RequestBody User user) {
        User usr = this.loginService.doLogin(user);
        if (usr != null) {
            return new ResponseEntity<User>(usr, HttpStatus.OK);
        } else {
            return new ResponseEntity<User>(HttpStatus.BAD_REQUEST);
        }
    }
}

I know there's a veeeeery stupid mistake, but I couldn't find it and I need your comparisons.

What's wrong?

Upvotes: 2

Views: 803

Answers (2)

Omkar Puttagunta
Omkar Puttagunta

Reputation: 4156

You have to use

hConf.addAnnotatedClass(Login.class).addAnnotatedClass(User.class);

instead of the addClass method.

From Hibernate Doc addAnnotatedClass

Source code from the Configuration class -

/**
     * Read a mapping as an application resource using the convention that a class
     * named <tt>foo.bar.Foo</tt> is mapped by a file <tt>foo/bar/Foo.hbm.xml</tt>
     * which can be resolved as a classpath resource.
     *
     * @param persistentClass The mapped class
     * @return this (for method chaining purposes)
     * @throws MappingException Indicates problems locating the resource or
     * processing the contained mapping document.
     */
    public Configuration addClass(Class persistentClass) throws MappingException {
        String mappingResourceName = persistentClass.getName().replace( '.', '/' ) + ".hbm.xml";
        LOG.readingMappingsFromResource( mappingResourceName );
        return addResource( mappingResourceName, persistentClass.getClassLoader() );
    }

    /**
     * Read metadata from the annotations associated with this class.
     *
     * @param annotatedClass The class containing annotations
     *
     * @return this (for method chaining)
     */
    @SuppressWarnings({ "unchecked" })
    public Configuration addAnnotatedClass(Class annotatedClass) {
        XClass xClass = reflectionManager.toXClass( annotatedClass );
        metadataSourceQueue.add( xClass );
        return this;
    }

From the above code, it is apparent that the addClass method looks for the mapping file and addAnnotatedClass will use Reflections to reads the metadata using the annotations of the class.

Upvotes: 1

Si mo
Si mo

Reputation: 989

The root cause of the exception is:

MappingNotFoundException: resource: it/grimi/babel/model/Login.hbm.xml not found

Please be sure this xml file exists.

You added the login class with "confiuration.addClass" the documentation of hibernate says "Hibernate will then search for mapping files named .../....hbm.xml in the classpath. "

Instead of this create a

"sessionFactory = new AnnotationConfiguration() .configure().buildSessionFactory();

and use annotations on your entities. https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html

https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/session-configuration.html

Upvotes: 1

Related Questions