Lenik
Lenik

Reputation: 14458

A simple question about Spring IoC

Let's imagine, there are 1000 classes (X1...X1000) which are all defined in a library abc.jar.

The X* classes have used some JSR-330 annotations, like:

class X12 {

    @Inject
    Foo foo;

    @Inject
    Bar bar;

}

My main class is a test case @RunWith(SpringJUnit4ClassRunner.class), and the referenced Foo, Bar are well defined in the bean XML files.

The question is, I don't want to define X1...X1000 in any XML files. But I'd like to auto wire them, for example:

X173 x173 = new X173();

But the problem is, using Java new instance, foo/bar isn't wired.

This also not works:

X173 x173 = applicationContext.getBean(X173.class);

because no bean for X173 is defined.

And, X173 may also contains a member of class X258 which should be wired, too. I can't figure out how to implement it until I've resolved this question.

Upvotes: 1

Views: 390

Answers (2)

Stan Kurilin
Stan Kurilin

Reputation: 15792

Ok. There is different types of testing. Let's look at too of them.

  • In modular testing you should test single class and mock it's dependency. So, you should avoid any injector.

  • In integration you should test some class's interaction, so you can use injector as in usual application.

Upvotes: 0

axtavt
axtavt

Reputation: 242726

You can use autodetection to declare them as Spring beans.

The most obvious way is to annotate these classes with Spring annotations such as @Component and then add <context:component-scan /> to your XML.

If annotating is not an option, <context:component-scan /> supports configurable filters. For example, if these classes are actually named X1...X1000, you can use regexp filter:

<context:component-scan base-package="com.example">
     <context:include-filter type="regex" expression="com\.example\.X\d{1,4}"/>
</context:component-scan>

Upvotes: 3

Related Questions