我创建了一个接口和一个类:
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"/>
很不幸,在测试开始时,Spring 抛出了异常:
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)}
我不确定哪里出了问题,为什么Spring找不到我定义的DefaultUserService
bean?
<bean>
声明在context-test.xml
文件中吗? - Sotirios Delimanolis<context:annotation-config />
吗?顺便问一下,在UserServiceTest
中不应该有一个userService
的setter方法吗? - Dan@Transactional
将bean放在jdk代理后面,详情请参考https://dev59.com/ZHbZa4cB1Zd3GeqPMPxp#18875681。您可以尝试使用属性占位符`@Value("${someprop}")`设置表名。或者创建另一个接口,其中包含`setTableName`,测试将引用该接口。我不确定是否有解决问题的简洁方法。 - Boris Treukhov