[英]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;
}
...
}
似乎沒有什么遺漏。
<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>
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.