为什么Spring没有将属性注入LocalContainerEntityManagerFactoryBean?

时间:2016-12-13 11:42:10

标签: spring hibernate spring-data spring-data-jpa jpa-2.0

我有以下配置类:

@Configuration
@PropertySource(value = "classpath:my.properties")
@EnableJpaRepositories("com.my.data.repository")
@EnableTransactionManagement
public class MyDataConfig {

    /* ... */

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        /* ... */
        return dataSource;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setDatabase(Database.ORACLE);
        jpaVendorAdapter.setDatabasePlatform(Oracle10gDialect.class.getName());
        jpaVendorAdapter.setGenerateDdl(false);
        jpaVendorAdapter.setShowSql(false);
        return jpaVendorAdapter;
    }

    @Bean
    public Properties jpaProperties() {
        Properties properties = new Properties();
        properties.put(AvailableSettings.FORMAT_SQL, false);
        properties.put(AvailableSettings.USE_SQL_COMMENTS, false);
        return properties;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        return transactionManager;
    }

    // WORKS
    @Bean
    public EntityManagerFactory entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter, Properties jpaProperties) {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setPackagesToScan("com.my.data.model");
        entityManagerFactory.setDataSource(dataSource);
        entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
        entityManagerFactory.setJpaProperties(jpaProperties);
        entityManagerFactory.afterPropertiesSet();
        return entityManagerFactory.getObject();
    }

    // DOES NOT WORK
    @Bean
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setPackagesToScan("com.my.data.model");
        // FIXME Spring should inject, shouldn't it?
        // entityManagerFactory.setDataSource(dataSource);
        // entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
        // entityManagerFactory.setJpaProperties(jpaProperties);
        entityManagerFactory.afterPropertiesSet();
        return entityManagerFactory.getObject();
    }

}

我不明白为什么我必须向LocalContainerEntityManagerFactoryBean提供咖啡豆(参见最后2种方法和差异),而我不必为其他豆类提供:

  • 数据源自动连接到HibernateJpaVendorAdapter;
  • 将任何内容(数据源,entityManagerFactory,jpaDialect ...)自动连接到JpaTransactionManager

或者我可能没有完全获得Spring magic ......

感谢。

PS:/* ... */条评论隐藏了一些繁琐的@Value("${...}"} private String xxx;字段,并将其设置为数据源(如驱动程序类,网址,用户,密码等)

0 个答案:

没有答案