我創建了一個接口和一個類:春天爲什麼找不到我的豆子?
public interface UserService {
List<User> listAll();
}
@Transactional
public class DefaultUserService implements UserService {
private String tableName;
public List<User> listAll() { someDao.listAllFromTable(tableName); }
public void setTableName(String tableName) { this.tableName = tableName; }
}
而且在我的應用程序上下文XML文件context.xml
,我定義:
<bean id="userService" class="mypackage.DefaultUserService">
<property name="tableName" value="myusers" />
</bean>
然後我要測試的DefaultUserService
:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:context-test.xml"})
@TransactionConfiguration(transactionManager = "testTransactionManager")
@Transactional
public class UserServiceTest {
@Autowired
private DefaultUserService userService;
@Before
public void setup() {
userService.setTableName("mytesttable");
}
@Test
public void test() {
// test with userService;
userService.listAll();
}
}
請注意,它使用context-test.xml
,它導入原始的context.xml
:
<import resource="classpath:context.xml"/>
不幸的是,在測試開始時,春拋出異常:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mypackage.UserServiceTest':
Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
private mypackage.DefaultUserService mypackage.userService
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [mypackage.DefaultUserService] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我不知道錯在哪裏,爲什麼春天找不到豆DefaultUserService
我定義?
的''宣告你已經是在'context-test.xml'中? –
你的意思是在第一個代碼塊中輸入'public class DefaultUserService'嗎? – Dan
@Sotirios,看到我更新的問題,我有這個聲明。 – Freewind