2011-04-21 43 views
6

使用@庫風格異常轉換如果我要聲明使用Spring 3的基於Java的配置的bean,我可以這樣做:距離Spring Java配置

@Configuration 
public class MyConfiguration { 
    @Bean 
    public MyRepository myRepository() { 
     return new MyJpaRepository(); 
    } 
} 

但是,因爲我不能使用@Repository在這種情況下的註釋,如何讓Spring執行異常轉換?

+0

爲什麼你不能使用'@ Repository'?你可以使用不同的註釋嗎? – skaffman 2011-04-21 13:57:43

+0

因爲這會從Spring的註釋掃描器創建組件,而不是從我的配置類創建。 – hertzsprung 2011-04-21 14:03:13

+0

@hertzspring:在這種情況下,重新配置掃描儀不要拿起班級。掃描器可以被賦予包含/排除規則。 – skaffman 2011-04-21 14:04:42

回答

4

聲明你MyJpaRepository類作爲存儲庫:

@Repository 
public class MyJpaRepository { 
    ... 
} 

並確保你有你的註釋通過在Spring配置中設置組件的掃描元件發現:

<context:component-scan base-package="org.example.repository"/> 

既然你做不希望您的存儲庫根據您的註釋包含在註釋掃描中,通過排除所有@Repository註釋或您的特定類或包來過濾它。有這樣的文檔中的一個示例:

<context:component-scan base-package="org.example.repository"> 
    <!-- use one or the other of these excludes, or both if you *really* want to --> 
    <context:exclude-filter type="regex" expression="*Repository"/> 
    <context:exclude-filter type="annotation" 
          expression="org.springframework.stereotype.Repository"/> 
</context:component-scan> 

Spring 3.0 documentation更詳細地描述該結構中在第3.10節。

通過將您的類配置爲Repository,當您在Configuration類中將它作爲Bean拉出時,它將被指定爲一個類。

+0

是的,看起來像'PersistenceExceptionTranslationPostProcessor'將找到Java配置以及註釋配置的bean。我最終使用自己的自定義註釋「@JavaConfiguredRepository」,並且添加了另一個PersistenceExceptionTranslationPostProcessor並重寫了其repositoryAnnotationType屬性。 – hertzsprung 2011-04-21 15:13:33