I am trying to autowire my datamodel class into various controller classes using the Autowired annotation and I keep getting a null pointer exception, I would like to keep my configuration XML based and avoid using the application context implementation if possible. a snippet of the code and spring-config file is below
Spring-Config
<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<bean id="datamodel" class="com.filemanager.datamodel.DataModel" autowire="byType"/>
</beans>
Data Model Class
public class DataModel {
private ObservableList<Song> windowDisplaySongs;
public void test() {
System.out.println("Hey, this is working");
}
public ObservableList<Song> getWindowDisplaySongs() {
return windowDisplaySongs;
}
public void setWindowDisplaySongs(ObservableList<Song> windowDisplaySongs) {
this.windowDisplaySongs = windowDisplaySongs;
}
}
Controller that has dependency on Model
public class FileBrowserController implements Initializable {
@Autowired
DataModel dataModel;
@Override
public void initialize(URL location, ResourceBundle resources) {
dataModel.test();
}
}
Things that I have tried
Using the component annotation above the model class, and above the model and controller class
Using the controller annotation above the controller class
Renaming the datamodel reference to match the name within the spring-config file
Using the qualifier annotation to specify that the datamodel reference should match the name in the spring config file.
Using the model reference in a method other than the init method
Removing the autowire="byType" from the config file
Creating an application context in the main method by using the code below, I was able to use the getBean() method with this, but I would like to use autowired to automatically inject the dependencies instead of having to call the getBean() method each time.
ApplicationContext ctx = new ClassPathXmlApplicationContext("config/spring-config.xml");
Following the solutions to other null pointer spring issues already on Stackoverflow: