gpt4 book ai didi

java - Spring + hibernate : Error bean creation

转载 作者:行者123 更新时间:2023-11-30 08:43:38 25 4
gpt4 key购买 nike

我正在开发一个 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

我很抱歉冗长......但异常本身更长,并且这个摘录应该(我猜)是它最重要的部分。

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

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

对,所以...这里是著名的类(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;
}

}

...我希望发布 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);
}
}
}

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

怎么了?

最佳答案

你必须使用

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

而不是 addClass方法。

来自 Hibernate 文档 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

关于java - Spring + hibernate : Error bean creation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34133027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com