Spring 事务配置(bean 与内部 class)

Spring transaction configruation (bean vs inner class)

在本书 Spring 中的示例中,我发现 TransactionManager 的配置是通过嵌套 class:

实现的
@Configuration
@ComponentScan
public class JpaConfig {

//EntityManagerFactory, JpaVendorAdapter, DataSource @Beans

  @Configuration
  @EnableTransactionManagement
  public static class TransactionConfig implements TransactionManagementConfigurer {
    @Inject
    private EntityManagerFactory emf;

    public PlatformTransactionManager annotationDrivenTransactionManager() {
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(emf);
      return transactionManager;
    }    
  }
}

这是一个好习惯还是什么?与标准的 @Bean 方法相比有什么不同吗:

@Configuration
@EnableTransactionManagement
public class DbConfig {

//EntityManagerFactory, JpaVendorAdapter, DataSource @Beans

    @Bean
    public JpaTransactionManager createTransactionManager(EntityManagerFactory emf) {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(emf);
        return jpaTransactionManager;
    }

}

还是只是职责分离?

Is it a good practice or something? Is there any difference in comparison to standard @Bean

正如您可能已经注意到的那样,这两种方法都有效。

第一种方法类似于inner bean概念。

如果您知道该 bean 不会被除外部 bean 之外的任何其他 bean 使用,那么您可以将其声明为内部 bean。这里的优点是,通过将 bean 设为内部 bean,您可以确保它不会暴露给外部 bean 以外的其他 bean,因此将无法 use/inject 其他 bean 中的内部 bean。

引自上文link

An inner bean definition does not require a defined id or name; if specified, the container does not use such a value as an identifier. The container also ignores the scope flag on creation: Inner beans are always anonymous and they are always created with the outer bean. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean or to access them independently.