![](/img/trans.png)
[英]Why Spring Boot is not finding a @Service bean trying to perform autowiring? the bean exist but it can't find it
[英]Why spring can't find my bean?
我創建了一個接口和一個類:
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無法找到我定義的bean DefaultUserService
?
嘗試將類DefaultUserService
替換為UserService
接口
public class UserServiceTest {
@Autowired
private UserService userService;
....
}
這是因為@Transactional
將bean放在實現UserService
接口的jdk代理后面,之后bean只能用作UserService
而不是DefaultUserService
。 請參閱https://stackoverflow.com/a/18875681/241986 。
您可以嘗試使用屬性占位符@Value("${someprop}")
設置表名,並在測試上下文中定義該屬性,或者創建另一個將公開setTableName()
接口,並將該幫助程序接口自動裝入測試用例。
我不確定是否有任何簡單的問題解決方案,我認為這個任務可以歸入Spring測試環境框架中的bean重新定義問題。單元測試環境中的Spring bean重新定義
您尚未在implementing class
為屬性tableName
定義getter
.Spring IOC
容器適用於POJO
模型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.