【问题标题】:Using @Repository-style exception translation from Spring Java configuration从 Spring Java 配置中使用 @Repository 样式的异常翻译
【发布时间】:2011-08-10 08:17:40
【问题描述】:

如果我想使用 Spring 3 的基于 Java 的配置声明一个 bean,我可以这样做:

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

但是,由于我不能在这种情况下使用@Repository注解,如何让Spring进行异常翻译?

【问题讨论】:

  • 为什么不能使用@Repository?你能改用其他注释吗?
  • 因为这会从 Spring 的注释扫描器创建组件,而不是从我的配置类。
  • @hertzspring:在这种情况下,重新配置扫描仪不要接你的课。可以为扫描器指定包含/排除规则。

标签: spring repository


【解决方案1】:

将您的 MyJpaRepository 类声明为存储库:

@Repository
public class MyJpaRepository {
  ...
}

并确保通过在 Spring 配置中设置组件扫描元素来发现注释:

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

由于您不希望您的存储库包含在每个 cmets 的注释扫描中,因此可以通过排除所有 @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,当您将其作为配置类中的 Bean 拉出时,它将被指定为一个。

【讨论】:

  • 是的,看起来 PersistenceExceptionTranslationPostProcessor 会发现 Java 配置的以及注解配置的 bean。我最终使用了我自己的自定义注释 @JavaConfiguredRepository,并添加了另一个 PersistenceExceptionTranslationPostProcessor 并覆盖了它的 repositoryAnnotationType 属性。
猜你喜欢
  • 1970-01-01
  • 2013-01-25
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 2011-08-27
  • 2012-03-05
相关资源
最近更新 更多