I got some null pointer exceptions when I try to access the fields from an injected object. I'm going to show a simple example. I'm using lokbok annotations @Getter
and @Setter
.
I have a simple class.
public class MyClass {
/*
* Field
*/
private @Getter @Setter String myName;
public MyClass(){
}
}
Then I another class
public class AnotherClass {
/*
* Field
*/
private MyClass myClass;
public AnotherClass(){
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
myClass = context.getBean("myClass", MyClass.class);
((ConfigurableApplicationContext) context).close();
myClass.setMyName("Hello");
}
}
If I access the field myName
from a third class, like this.
public class ThirdClass {
/*
* Field
*/
private MyClass myClass;
public ThirdClass(){
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
myClass = context.getBean("myClass", MyClass.class);
((ConfigurableApplicationContext) context).close();
System.out.println(myClass.getMyName());
}
}
It will print out null
as output. I have created my Beans.xml file like this:
<?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">
<!-- Create my class -->
<bean id="myClass" class="MyClass"></bean>
</beans>
Questions:
Should it behave like that?
Have I missed something if I don't want to have null
?
Software being used:
- JavaFX 8
- Java 8
- Gluon-Ignite Spring 1.0.2
- Lombok 1.18.8