I have the following scenario:
A bean Autowired in two classes, I populate the bean in one class, then I check the bean in the second class, it is not populated. Whereas, when I add a getter in the class where I populated the bean and call the getter, it returns the bean populated. Why can't I access that bean directly in the other class, shouldn't it be populated since it's acting as a singleton in spring context?
A JUnit4 test class loading the spring context from an xml file:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/test-main-context.xml" })
public class MyTests {
@Autowired
MyObject myObject;
@Autowired
MyUtils myUtils;
@Test
public void testingContext() {
myUtils.setMyObjectFromDB();
System.out.println(myUtils.getMyObject().getId());
System.out.println(myObject.getId());
}
}
MyUtils:
public class MyUtils {
@Autowired MyObject myObject;
public void setMyObjectFromDB() {
MyObject myDBObject = new MyObject();
//
// getting myObjectFromDB;
//
myObject = myDBObject;
}
public MyObject getMyObject() {
return myObject;
}
}
In the test class, myUtils.getMyObject().getId()
returns a correct id but the second line myObject.getId()
it returns null.
Why is MyObject which is set in MyUtils class and is @Autowired in both classes is not being updated when I access it directly in the test class.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…