8

我昨晚花了很多时间试图弄清楚这一点。我有一个 HSQLDB 服务器正在运行,我可以使用 JDBC 驱动程序连接到它。任务的下一部分是做同样的事情,但使用 Spring 框架。我声明了我的 bean,创建了我的 DAO 类,但程序没有连接到服务器。由于这是我们第一次使用 JdbcTemplate,我们不应该进行自动装配。这是我拥有的文件:

JdbcUserDAO

public class JdbcUserDAO extends JdbcDaoSupport
                    implements UserDAO {

    public User getUserWithId(int id) {
        return new User(1,"gamda","test");
    }

    public int howManyUsers() {
        JdbcTemplate test = getJdbcTemplate();
        System.out.println("Got template");

        try {
            getConnection();
            System.out.println("Got connection");   
        } catch (Exception e) {
            System.out.println("Not connecting");
        }


        int result = test.queryForInt("select count from users");
        System.out.println("Query success");
        return result;
    }

}

beans.xml(与我的 .java 文件在同一个文件夹中,如果有区别的话)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDAO" class="com.project2.db.JdbcUserDAO">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="questionDAO" class="com.project2.db.JdbcQuestionDAO">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

    <bean id="answerDAO" class="com.project2.db.AnswerDAO">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
    destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver"/>
        <property name="url" value="jdbc:hsqldb:hsql://localhost/cpsc476;ifexists=true"/>
        <property name="username" value="SA"/>
        <property name="password" value="Passw0rd"/>
    </bean>
</beans>

蚂蚁的build.xml

<project 
    name="DB_Access" 
    default="compile" 
    xmlns:artifact="antlib:org.apache.maven.artifact.ant">

<target name="init">
    <mkdir dir="classes" />
</target>

<target name="clean">
    <delete dir="classes" />
    <delete dir="jar" />
</target>

<target name="compile" depends="init">
    <javac srcdir="src"
           destdir="classes">
        <classpath refid="dependency.classpath" />
    </javac>
</target>

<target name="run" depends="compile">
    <java classname="com.project2.db.ListQuestionsAndAnswers">
        <classpath>
            <path refid="dependency.classpath" />
            <path location="classes/" />
        </classpath>
    </java>
</target>

<target name="jar" depends="compile">
    <mkdir dir="jar" />
    <jar destfile="jar/db.jar" basedir="classes">
        <manifest>
            <attribute name="Main-Class" value="com.project2.db.dbCon" />
        </manifest>
    </jar>
</target>

<artifact:dependencies 
    pathId="dependency.classpath"
    filesetId="dependency.fileset">
    <dependency
        groupId="org.springframework"
        artifactId="spring-jdbc"
        version="3.2.4.RELEASE" />

    <dependency
        groupId="org.springframework"
        artifactId="spring-beans"
        version="3.2.4.RELEASE"/>

    <dependency
        groupId="org.springframework"
        artifactId="spring-context"
        version="3.0.2.RELEASE"/>

    <dependency
        groupId="org.hsqldb"
        artifactId="hsqldb"
        version="2.3.0" />
    <dependency
        groupId="commons-dbcp"
        artifactId="commons-dbcp"
        version="1.4" />
</artifact:dependencies>
</project>

我正在使用的测试类:阅读提供的教程后编辑

public class ListQuestionsAndAnswers {
    public static int main( String[] args ) {

        ApplicationContext appContext = new ClassPathXmlApplicationContext(
        "beans.xml");

        JdbcUserDAO test = (JdbcUserDAO) appContext.getBean("userDAO"); 
        int answer = test.howManyUsers();
        System.out.println(answer);
        return 0;
    }
}

当我执行“ant run”时,这是输出:Edited because it's a new error

 >[java] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is java.lang.NoSuchFieldError: NULL
 >[java]    at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:194)
 >[java]    at org.apache.tools.ant.taskdefs.Java.run(Java.java:771)
 >[java]    at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:221)
 >[java]    at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:135)
 >[java]    at org.apache.tools.ant.taskdefs.Java.execute(Java.java:108)
 >[java]    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
 >[java]    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 >[java]    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 >[java]    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 >[java]    at java.lang.reflect.Method.invoke(Method.java:606)
 >[java]    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
 >[java]    at org.apache.tools.ant.Task.perform(Task.java:348)
 >[java]    at org.apache.tools.ant.Target.execute(Target.java:435)
 >[java]    at org.apache.tools.ant.Target.performTasks(Target.java:456)
 >[java]    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
 >[java]    at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
 >[java]    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
 >[java]    at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
 >[java]    at org.apache.tools.ant.Main.runBuild(Main.java:851)
 >[java]    at org.apache.tools.ant.Main.startAnt(Main.java:235)
 >[java]    at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
 >[java]    at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
 >[java] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is java.lang.NoSuchFieldError: NULL
 >[java]    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
 >[java]    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
 >[java]    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
 >[java]    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
 >[java]    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
 >[java]    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
 >[java]    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
 >[java]    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)
 >[java]    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
 >[java]    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
 >[java]    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
 >[java]    at com.project2.db.ListQuestionsAndAnswers.main(Unknown Source)
 >[java]    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 >[java]    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 >[java]    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 >[java]    at java.lang.reflect.Method.invoke(Method.java:606)
 >[java]    at org.apache.tools.ant.taskdefs.ExecuteJava.run(ExecuteJava.java:217)
 >[java]    at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:152)
 >[java]    ... 21 more
 >[java] Caused by: java.lang.NoSuchFieldError: NULL
 >[java]    at org.springframework.expression.TypedValue.<clinit>(TypedValue.java:31)
 >[java]    at org.springframework.expression.spel.support.StandardEvaluationContext.setRootObject(StandardEvaluationContext.java:82)
 >[java]    at org.springframework.expression.spel.support.StandardEvaluationContext.<init>(StandardEvaluationContext.java:71)
 >[java]    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:124)
 >[java]    at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1312)
 >[java]    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.evaluate(BeanDefinitionValueResolver.java:225)
 >[java]    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:312)
 >[java]    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
 >[java]    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1387)
 >[java]    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
 >[java]    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
 >[java]    ... 38 more
 >[java] Java Result: -1  

所以我知道我的 JdbcTemplate 不为空,但它无法连接到数据库,我不知道如何检查连接或使其连接。

4

1 回答 1

5

您已定义JdbcUserDAO为带有 id 的 spring bean ,但是您正在使用不会处理其依赖关系的操作符userDAO创建它的实例new

您需要初始化spring bean上下文,然后从上下文中获取bean

于 2013-10-17T16:46:05.723 回答