2015-04-05 111 views
2

當這個bean創建一個類爲MyBean的bean id爲myBean但是如果我從下面的接口創建服務bean,那麼bean ID是什麼?什麼是spring bean的bean ID實現了一個接口

@Service 
public class ProfileServiceImpl implements ProfileService 

當我嘗試爲@profileService thymeleaf給下面的錯誤訪問豆。

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'profileService' is defined 

所有這一次,我使用這個豆由autowiring控制器。但目前我需要從thymeleaf訪問這個。

我thymeleaf代碼段

<div th:unless="${@profileService.isMe(user)}"> 

回答

2

當Spring通過@Service或@Component註釋創建Bean定義時,它將默認通過壓縮Class Name的第一個字母來爲bean創建一個id。如果你想覆蓋這個行爲,你可以在註釋中提供一個替代的id,例如。 @Service( 「profileService」)。

關於您在存儲庫中遇到的情況 - 默認情況下,Spring通過將「Impl」附加到存儲庫接口名稱來查找存儲庫的自定義實現。如果發現它,它不會創建默認實現。所以,如果你有UserRepositoryImpl extends UserRepository而不是UserRepositoryImpl extends DatatablesCriteriasRepository比Spring不會創建userRepository bean。另外,如果將@NoRepositoryBean註釋添加到UserRepository接口,則會禁止創建userRepository bean。

然而,UserRepositoryImpl確實應該實施UserRepository。如果它確實打算延長DatatablesCriteriasRepository,則應該將其命名爲DatatablesCriteriasRepositoryImpl。有UserRepsitoryImpl擴展DatatablesCriteriasRepository表示設計中存在問題。

+0

謝謝你的回答。但與代碼設計有關,我在單獨的問題中發佈了我的問題。希望你也可以看看它。 http://stackoverflow.com/questions/29467886/implementing-crudrepository-in-spring-whats-the-best-design-i-should-follow – 2015-04-06 08:35:38

0
for (String name : context.getBeanDefinitionNames()){ 
    System.out.println(name); 
} 

該測試揭示了一些有趣的結果。

服務豆

服務豆類具體的類名來命名不管接口。

@Service 
public class ProfileServiceImpl implements ProfileService 

即, profileServiceImpl在上面的問題。

庫豆

而且庫豆類更有趣的東西。下面是我的粗暴倉庫界面,沒有任何註釋。

public interface UserRepository extends CrudRepository<User, Long>, DatatablesCriteriasRepository<User>{ 

我創建了UserRepositoryImplDatatablesCriteriasRepository如下的實現沒有任何註釋。

public class UserRepositoryImpl implements DatatablesCriteriasRepository<User> 

這兩個分別userRepositoryuserRepositoryImpl包括二豆的ID。