I'm getting a null pointer when I try to access and use a SimpleJdbcDaoSupport
. This is how I'm working it out:
In the main class
@Override
public void start(final Stage primaryStage) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
SimpleJdbcDaoImpl dao = ctx.getBean("simpleJdbcDaoImpl", SimpleJdbcDaoImpl.class);
In some other stage controller class
public class HomeController implements Initializable {
@Autowired
private SimpleJdbcDaoImpl simpleJdbcDaoImpl;
// Initializes the controller class.
@Override
public void initialize(URL url, ResourceBundle rb) {
// Stage and the rest called
}
@FXML
public void showNewCalendarStage() throws Exception {
System.out.println(simpleJdbcDaoImpl.getCircleCount());
}
The SimpleJdbcDaoSupport
class
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class SimpleJdbcDaoImpl extends SimpleJdbcDaoSupport {
public int getCircleCount() {
String sql = "SELECT COUNT(*) FROM KIWI_TABLE";
return this.getJdbcTemplate().queryForInt(sql);
}
}
The 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:file:C:/WAKILI/WAKILIdb"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="simpleJdbcDaoImpl" class="wakiliproject.dao.SimpleJdbcDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation">
<value>
classpath:/hibernate.cfg.xml
</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<context:annotation-config/>
<context:component-scan base-package="wakiliproject"/>
</beans>
The error:
Caused by: java.lang.NullPointerException
at HomeController.showNewCalendarStage(HomeController.java:283)
... 42 more
I'm trying to teach myself Spring and would like to, for example, populate a Label
in another Controller class (other than the main class) with text retrieved from the database.
For simplicity, in this case, lets print some text from the database to the console. What am I doing wrong with the above code? Thank you all.