Samo
Samo

Reputation: 8240

So NOW why is my bean null?

I recently asked this question regarding pulling beans out of an applicationContext. The answer was indeed helpful, but now it seems I have a problem with accessing this bean from a class outside the test. In other words, my test instantiates a class which uses a bean from an application context, but this bean keeps coming up null.

My test sets up the application context like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class SearcherTests {

My test programmatically instantiates the Repository class:

    Repository searcher = new Repository();

My Repository class has the following member variable:

 @Resource
 private MyFactory myFactory;

If I understand Spring correctly, this should look to the current application context for a bean named myFactory. According to the test, the current application context should be applicationContext-test.xml, which contains a definition for myFactory:

 <bean id="myFactory" 
    name="myFactory" 
    class="com.foo.Mocks"
    factory-method="createMockFactory" />

In the future, this factory method will return a mock. But at the moment, it just returns a regular Factory object:

public class Mocks {

 public static MyFactory createMockFactory() {
  return new MyFactory();
 }
}

When I run the app from my browser, the myFactory variable was correctly instantiated from the bean definition in applicationContext.xml. In my test, to make sure that my applicationContext-test.xml is working, I have this same bean listed as a member variable just like I do in the Repository class. While running the test, the myFactory variable in the file containing the test looks exactly as I'd expect it to. However, when I get to the Repository class, the myFactory variable in that class is null. It seems as though this class is not instantiating the myFactory variable based on the bean definition in applicationContext-test.xml. Can someone tell me why?

Update

I changed the searcher variable so that it is a Spring bean, rather than instantiating the Repository class manually, and now the myFactory variable has been populated within the Repository class. Can someone explain why this needs to be a bean in order to work?

Upvotes: 3

Views: 620

Answers (1)

skaffman
skaffman

Reputation: 403441

If you instantiate Repository yourself, then Spring doesn't get involved, and the dependencies won't get injected. It doesn't happen magically, Spring has to be in the loop somehow - the instance has to be passed through Spring processing layers, and a direct instantiation prevents that.

Upvotes: 3

Related Questions