当我尝试通过不同类的 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)
8
是 System.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 只能填充注入(inject)/ Autowiring 的资源。
你必须:
- 用
@Service
注释 SomeOtherClass - 通过
ctx.getBean(SomeOtherClass.class).printDb();
从 spring 上下文中获取该类
关于java - 如何在不同的类中使用 Spring Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25015868/