First of all, to quote the javadoc of @ContextConfiguration
@ContextConfiguration
defines class-level metadata that is used to determine how to load and configure anApplicationContext
for integration tests.
Consider how you are using it on OuterService
. Does it seem right? Is OuterService
meant to be used to load and configure an ApplicationCOntext
for integration tests? Unless I'm missing something essential, the answer is: No.
So what is OuterService
? It's some kind of service. You seem to want to use it as a bean. What is a bean? A bean is an object whose lifecycle is managed by Spring. This includes instantiation of the bean class, initialization of the object, post processing, and, finally, destruction of the object.
If you created the object like so
OuterService os = new OuterService();
then Spring is not involved. You created the object and there is no way for Spring to hook into that. You cannot therefore expect Spring to autowire its field
@Autowired
private Dao dao;
And since you haven't initialized the field, it remains null
, which causes the NullPointerException
.
So how do we get an OuterService
bean, which is managed by Spring? You either declare a @Bean
method for OuterService
or you annotate OuterService
with @Component
or any of its specializations and component-scan the package it is in. You then inject the bean into any other bean that uses it. For example,
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader=AnnotationConfigContextLoader.class)
public class TutorialTest {
@Autowired
private Dao dao;
@Autowired
private OuterService os;
You can then use that variable directly.