簡體   English   中英

僅運行測試時,Bean自動裝配失敗

[英]Bean autowire fail when running tests only

希望有人可能對此問題有答案。 運行測試時出現自動接線問題,其他情況則沒有。 異常很清楚,因為它說缺少“ myField”。 但是,該字段是從基類繼承的。 我在任何地方都找不到解決問題的答案,因此我將在這里嘗試好運。

例外

org.springframework.beans.factory.BeanCreationException: 
    Error creating bean with name 'myService': Injection of autowired dependencies failed; 
    nested exception is java.lang.NoSuchFieldError: myField

我的基礎班

public abstract class CommonStuff {
    protected String myField; // the one thats gone missing
    public abstract void setMyField(String myField);
}

我的服務

@Service("myService")
public class MyService extends CommonStuff {
    @Value("${myProperty.myField}")
    public void setMyField(String myField) {
        this.myField = myField;
    }
    ...
}

我的控制器

@Controller
public class MyController {
    @Autowired
    private MyService myService;        
    public void setMyService(MyService myService) {
        this.myService = myService;
    }
    ...
}

我的application-context.xml

似乎沒有什么遺漏。

<context:component-scan base-package="com.myapp" />
<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:my.properties</value>              
            <value>classpath:myother.properties</value>
        </list>
    </property>
</bean>

my.properties

myProperty.myField=some value

我的測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-context.xml" })
public class MyControllerTest {
    @Autowired
    MyController myController;

    @Mock
    MyService myService;

    @Test
    public void myServiceTest() {
        // do stuff with myService
    }
    ...
}

問題

正如我提到的那樣,代碼運行正常,但是每當我嘗試運行測試時,彈簧都無法自動裝配。

問題不是測試,而是開始測試時的接線。 spring某種程度上無法從抽象的CommonStuff類中找到myField,因此它說MyService沒有該字段。

如果需要,我可以發布完整的stacktrace,但是我認為異常的實質已經在這里。

我放棄了並將myField移回到服務中,並跳過了setMyField。 現在就是這樣。

基類

public abstract class CommonStuff {    
    public abstract String getMyField();
    public void doCommonStuff() {
        // use getMyField() 
    }
}

我的服務

@Service("myService")
public class MyService extends CommonStuff {
    @Value("${myProperty.myField}")
    private String myField;

    @Override
    public String getMyField() {
        return myField;
    }
    ...
}

這解決了我想要的問題,因為我現在可以從CommonStuff訪問myField。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM