简体   繁体   中英

Autowired in JUnit: only binds fields in Test class, not in other classes

I have the following Test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/**/context.xml")
public class HAD_Test extends TestCase {

    @Autowired
    private UgcService ugcService;

    @Test
    public void test() {
        // this binding works fine
        Ugc ugc = ugcService.getRegistro(138355);
        ...
        HAD_Data dData = new HAD_Data(ugc);
        data.init();
        ...
    }
}

Then I have this other class:

public class HAD_Data {
    @Autowired
    private ClimaService climaService;

    public void init() {
        ...
        // at this point, climaService is null
        climaService.getRegistro(556)
        ...
    }
}

The problem I'm having, is that the bindings in the Test class are being applied perfectly, but in any class I use, like HAD_Data, where there exist other autowired fields, these ones are not binded. They always have a null value.

I don't really know why these bindings are not been assigned. Can anybody help me please? If any other information is necessary, I can include it, but I think that my context.xml is correct, cause there exist some bindings applied ok.

Thanks, Marc

How do you expect Spring to inject the field if you are the one creating the object?

HAD_Data dData = new HAD_Data(ugc);

Spring can only autowire managed beans.

Add a bean declaration in your context.xml for HAD_Data and use that. You can also use @PostConstruct on the init() method so that Spring takes care of calling it after initialization.


Also, note that Java conventions discourage the use of _ in class names.

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