简体   繁体   中英

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.

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM