I'm sure I'm missing something simple. bar gets autowired in the junit test, but why doesn't bar inside foo get autowired?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"beans.xml"})
public class BarTest {
@Autowired
Object bar;
@Test
public void testBar() throws Exception {
//this works
assertEquals("expected", bar.someMethod());
//this doesn't work, because the bar object inside foo isn't autowired?
Foo foo = new Foo();
assertEquals("expected", foo.someMethodThatUsesBar());
}
}
When @Autowired doesn't work. There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.
To check the Service class, we need to have an instance of the Service class created and available as a @Bean so that we can @Autowire it in our test class. We can achieve this configuration using the @TestConfiguration annotation.
If the application starts and your field appears to be null it is generally due to one of the following issues: Using @Autowired on a static field. Omitted @Autowired on a field. Instance of bean not visible to Spring.
The beans can be wired via constructor or properties or setter method. For example, there are two POJO classes Customer and Person. The Customer class has a dependency on the Person. @Autowired annotation is optional for constructor based injection.
Foo isn't a managed spring bean, you are instantiating it yourself. So Spring's not going to autowire any of its dependencies for you.
You are just creating a new instance of Foo. That instance has no idea about the Spring dependency injection container. You have to autowire foo in your test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"beans.xml"})
public class BarTest {
@Autowired
// By the way, the by type autowire won't work properly here if you have
// more instances of one type. If you named them in your Spring
// configuration use @Resource instead
@Resource(name = "mybarobject")
Object bar;
@Autowired
Foo foo;
@Test
public void testBar() throws Exception {
//this works
assertEquals("expected", bar.someMethod());
//this doesn't work, because the bar object inside foo isn't autowired?
assertEquals("expected", foo.someMethodThatUsesBar());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With