当我尝试通过SimpleJdbcDaoSupport getJdbcTemplate()从不同的类(在这种情况下为类SomeOtherClass)中打印数据库项目时遇到问题。

我的实现是这样的:

主类:

public class JdbcDemo {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

        HibernateDaoImpl dao = ctx.getBean("hibernateDaoImpl", HibernateDaoImpl.class);
        System.out.println(dao.getCircleCount());
        new TestController().printDb();
    }
}


其他一些SomeOtherClass类:

public class SomeOtherClass {

    @Autowired
    private SimpleJdbcDaoImpl simpleJdbcDaoImpl;

    public void printDb() {
        System.out.println(simpleJdbcDaoImpl.getCircleCount() + " : trial here.....");
    }
}


System.out.println(dao.getCircleCount());中的JdbcDemo可以正常工作,但new TestController().printDb();中的SomeOtherClass则不能。为什么会这样?

堆栈跟踪:

8
Exception in thread "main" java.lang.NullPointerException
    at com.rev.TestController.printDb(TestController.java:12)
    at com.rev.JdbcDemo.main(JdbcDemo.java:17)
Java Result: 1
BUILD SUCCESSFUL (total time: 35 seconds)


8System.out.println(dao.getCircleCount());的输出

我在哪里扩展SimpleJdbcDaoSupport

public class SimpleJdbcDaoImpl extends SimpleJdbcDaoSupport {

    public int getCircleCount() {
        String sql = "SELECT COUNT(*) FROM CIRCLE";
        return this.getJdbcTemplate().queryForInt(sql);
    }
}


我将不胜感激任何帮助。谢谢。

更新:

spring.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:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver"/>
        <property name="url" value="jdbc:h2:D:\\WAKILI\\jdbcdemodb"/>
    </bean>

    <bean id="simpleJdbcDaoImpl" class="com.rev.dao.SimpleJdbcDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.rev.model" />

        <property name="hibernateProperties">
            <props>
                <prop key="dialect">org.hibernate.dialect.H2Dialect</prop>
            </props>
        </property>
    </bean>


    <context:annotation-config/>
    <context:component-scan base-package="com.rev"/>

</beans>

最佳答案

如果封闭的类本身是spring托管的bean,则Spring只能填充注入的/自动装配的资源。

你必须:


@Service注释SomeOtherClass
通过ctx.getBean(SomeOtherClass.class).printDb();从spring上下文中获取该类

09-05 04:28