spring 使用在 ServletContext 资源中定义的名称“dataSource”创建 bean 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12558250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error creating bean with name 'dataSource' defined in ServletContext resource
提问by Pirzada
I am working on struts2 demo project and spring to manage Hibernate sessions.
我正在使用 struts2 演示项目和 spring 来管理 Hibernate 会话。
I am following this article http://www.splinter.com.au/using-spring-to-manage-hibernate-sessions-in/
我正在关注这篇文章http://www.splinter.com.au/using-spring-to-manage-hibernate-sessions-in/
ERROR
错误
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NoSuchFieldError: NULL
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.NoSuchFieldError: NULL
at org.springframework.expression.TypedValue.<clinit>(TypedValue.java:32)
at org.springframework.expression.spel.support.StandardEvaluationContext.setRootObject(StandardEvaluationContext.java:85)
at org.springframework.expression.spel.support.StandardEvaluationContext.<init>(StandardEvaluationContext.java:74)
at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:124)
at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1299)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.evaluate(BeanDefinitionValueResolver.java:210)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:182)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 21 more
Sep 24, 2012 7:22:18 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Sep 24, 2012 7:22:18 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/1-Struts2_CRUD] startup failed due to previous errors
Sep 24, 2012 7:22:18 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Sep 24, 2012 7:22:18 AM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
SEVERE: The web application [/1-Struts2_CRUD] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Sep 24, 2012 7:22:18 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/1-Struts2_CRUD] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
applicationContext.xml
应用上下文.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- enable annotation beans definitions -->
<context:component-scan base-package="com.pirzada"/>
<!-- Basic DataSource Configuration -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/struts2_demo_db"/>
<property name="username" value="root"/>
<property name="password" value="786"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.pirzada.dao</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.max_fetch_depth">0</prop>
<prop key="hibernate.jdbc.use_scrollable_resultset">true</prop>
</props>
</property>
</bean>
<!-- defining transaction manager bean using Hibernate -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- <!– exception translation bean post processor –>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>-->
<!-- DAO beans -->
<!--
<bean id="userDAO" class="org.droidaceapps.dao.UserDAOImpl">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<!– Service beans –>
<bean id="userService" class="org.droidaceapps.services.UserServiceImpl">
<property name="userDAO" ref="userDAO" />
</bean>-->
</beans>
web.xml
网页.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!--<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring -->
<listener> <!-- Required for the struts2 spring plugin to work -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter> <!-- Get spring to keep the session open for the whole request, so hibernate's lazy loads work -->
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Hibernate.cfg.xml
休眠文件.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/struts2_demo_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">786</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Echo all executed SQL to stdout for debugging -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.idle_test_period">30</property>
<mapping class="com.pirzada.domain.User"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
UserDAOImpl
用户DAOImpl
/*@Transactional is needed so that a Hibernate transaction is set up, otherwise updates won't have an affect*/
@Transactional
public class UserDAOImpl implements UserDAO {
// So Spring can inject the session factory
protected SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory value) {
sessionFactory = value;
}
// Shortcut for sessionFactory.getCurrentSession()
protected Session session() {
return sessionFactory.getCurrentSession();
}
@Override
public void saveOrUpdateUser(User user) {
session().saveOrUpdate(user);
}
}
maven
行家
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- javaee-api 6 dependencies -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring framework dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.4.1</version>
</dependency>
<!-- struts2 dependencies -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.4.1</version>
</dependency>
<!-- sl4j dependencies -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- Hibernate dependencies -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.core.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.core.version}</version>
</dependency>
<!-- JDBC dependencies -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
</dependencies>
回答by Stanislav Bashkyrtsev
It looks to be a problem with incompatible versions of JAR files in the classpath, for instance Spring may need some lower or higher version of hibernate. hibernate.core.version- this would be useful to see. Try using Hibernate3 instead, I bet it's a problem with Hibernate4 and its Spring support.
看起来是类路径中 JAR 文件版本不兼容的问题,例如 Spring 可能需要一些较低或较高版本的 hibernate。hibernate.core.version- 这会很有用。尝试改用 Hibernate3,我敢打赌这是 Hibernate4 及其 Spring 支持的问题。
回答by Jon Tinsman
I can't offer a solution, but since I can't comment as I do not have enough points I can give you what information I have gotten in hopes you are able to find a solution as well.
我无法提供解决方案,但由于我没有足够的积分而无法发表评论,因此我可以向您提供我所获得的信息,希望您也能够找到解决方案。
I am getting the same error when I am trying to run a sample project. I am running Hibernate 3.2.0.ga, Maven 2, Spring 3.2.0 and Tomcat 7. I get the exact error. I downloaded the source files, put in a break and ran Tomcat on debug. From what I can tell. I am getting the error when it is trying to get the registered scopes. What the Beans are passing in is "singleton" and when it looks for that scope it returns null and I get the error you described.
当我尝试运行示例项目时,我遇到了同样的错误。我正在运行 Hibernate 3.2.0.ga、Maven 2、Spring 3.2.0 和 Tomcat 7。我得到了确切的错误。我下载了源文件,暂停并在调试时运行Tomcat。据我所知。尝试获取注册范围时出现错误。Beans 传入的是“singleton”,当它查找该范围时,它返回 null 并且我收到您描述的错误。
I, for sanity sake, added "session" to all my beans and I get a different error
为了理智起见,我为所有 bean 添加了“会话”,但出现了不同的错误
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
...
I hope that this might put you on the right track to solve this as I would love to find the solution as well. Setting up the projects and the project infrastructure is my weak point so this is always a head-banger for me.
我希望这可以让您走上正确的道路来解决这个问题,因为我也很想找到解决方案。设置项目和项目基础设施是我的弱点,所以这对我来说总是很头疼。
EDIT: Sure enough, it is most likely a library version conflict. On my project I was initially trying to go with the latest of the Spring and Hibernate 3 when I was getting the error. I Googled and Googled to find out which versions were compatible with each other and found one old comment from a Hibernate forum that showed Spring 3.0.0.RELEASE will work with Hibernate 3.4.0.GA. I plan on updating each until I can get to the latest compatible versions for the two tools.
编辑:果然,很可能是库版本冲突。在我的项目中,当我遇到错误时,我最初尝试使用最新的 Spring 和 Hibernate 3。我用谷歌搜索和谷歌搜索以找出哪些版本彼此兼容,并在 Hibernate 论坛上找到了一条旧评论,该评论显示 Spring 3.0.0.RELEASE 将与 Hibernate 3.4.0.GA 一起使用。我计划更新每一个,直到我可以获得这两个工具的最新兼容版本。
Someone on a SO comment had said
有人在 SO 评论上说过
Just play around with the libraries until you find some that are compatible. Isn't that one of the fun parts of being a developer?
只需使用库,直到找到兼容的库。这不是成为开发人员的乐趣之一吗?
... I sure hope that guy was being facetious.
......我当然希望那个人是开玩笑的。
回答by Nguyen Tran
You should add mysql-connector-java-5.1.26-bin.jar into WEB-INF/lib. I met problem like you. It'll work.
您应该将 mysql-connector-java-5.1.26-bin.jar 添加到 WEB-INF/lib 中。我遇到了你这样的问题。它会工作。

