Spring + Hibernate:错误bean创建

时间:2015-12-07 11:58:07

标签: java spring hibernate spring-mvc

我正在开发一个Spring MVC + Hibernate Web应用程序,我遇到了这个例外:

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

我道歉这个冗长......但是异常本身就更长了,这个摘录应该(我猜)是最重要的部分。

我知道LoginDao中的LoginDaoImpl声明有问题(不是吗?)但是我无法弄清楚是什么(实际上由于我的原因我也很难理解它使用Spring的早期技能,所以,我需要一些帮助)

我跟着this示例尝试根据我的项目要求更改某些内容。这显然是一个做得很好的例子,我的应用程序基本上具有相同的结构,但它还有SingleSessionFactory类(如下所示)包装所有配置以使Hibernate与数据库对话(因为xml让我生病)。

是的,所以...这里是着名的班级:

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

}

...我希望发布LoginDaoImplLoginServiceImpl类和MainRestController类作为REST API的入口点。

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

我知道这是一个愚蠢的错误,但我找不到它,我需要你的比较。

怎么了?

2 个答案:

答案 0 :(得分:1)

异常的根本原因是:

  

MappingNotFoundException:resource:it / grimi / babel / model / Login.hbm.xml   找不到

请确保此xml文件存在。

你用“confiuration.addClass”添加了登录类,hibernate的文档说“然后Hibernate将在类路径中搜索名为... / .... hbm.xml的映射文件。”

而不是创建一个

  

“sessionFactory = new AnnotationConfiguration()                       。.configure()buildSessionFactory();

并在您的实体上使用注释。 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

答案 1 :(得分:1)

你必须使用

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

而不是addClass方法。

来自Hibernate Doc addAnnotatedClass

来自Configuration类的源代码 -

/**
     * 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;
    }

从上面的代码中可以看出,addClass方法查找映射文件,addAnnotatedClass将使用Reflections使用annotations的{​​{1}}来读取元数据。类。