我有以下配置类:
@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
; JpaTransactionManager
。或者我可能没有完全获得Spring magic ......
感谢。
PS:/* ... */
条评论隐藏了一些繁琐的@Value("${...}"} private String xxx;
字段,并将其设置为数据源(如驱动程序类,网址,用户,密码等)