简体   繁体   English

在JUnit中自动连线:仅绑定Test类中的字段,而不绑定其他类中的字段

[英]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. 我遇到的问题是Test类中的绑定被完美地应用了,但是在我使用的任何类中(例如HAD_Data),如果存在其他自动连接的字段,这些字段都不会被绑定。 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. 如果有任何其他信息是必要的,我可以包括在内,但是我认为我的context.xml是正确的,因为存在一些应用的绑定可以。

Thanks, Marc 谢谢,马克

How do you expect Spring to inject the field if you are the one creating the object? 如果您是创建对象的人,您如何期望Spring注入字段?

HAD_Data dData = new HAD_Data(ugc);

Spring can only autowire managed beans. Spring只能自动连线托管的bean。

Add a bean declaration in your context.xml for HAD_Data and use that. context.xmlHAD_Data添加一个bean声明并使用它。 You can also use @PostConstruct on the init() method so that Spring takes care of calling it after initialization. 您还可以在init()方法上使用@PostConstruct ,以便Spring初始化后负责对其进行调用。


Also, note that Java conventions discourage the use of _ in class names. 另外,请注意,Java约定不鼓励在类名中使用_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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