【发布时间】:2015-07-30 10:00:47
【问题描述】:
我正在使用 Spring Boot Data JPA,现在,我有这个:
@Configuration
@PropertySource("classpath:persistence.properties")
@EnableTransactionManagement
public class PersistenceConfiguration {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(this.dataSource());
entityManager.setPackagesToScan(new String[] {"com.example.movies.domain"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManager.setJpaVendorAdapter(vendorAdapter);
entityManager.setJpaProperties(this.properties());
return entityManager;
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private Properties properties() {
Properties properties = new Properties();
properties.setProperty("hibernate.ddl-auto", this.env.getProperty("spring.jpa.hibernate.ddl-auto"));
properties.setProperty("hibernate.dialect", this.env.getProperty("spring.jpa.hibernate.dialect"));
properties.setProperty("hibernate.show_sql", this.env.getProperty("spring.jpa.show-sql"));
return properties;
}
}
还有我的persistence.properties
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/sarasa_db
spring.datasource.username=root
spring.datasource.password=myPassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
我想知道是否有任何方法可以自动加载这些 JpaProperties。我想要那个spring构建它,因为现在,如果我在persistence.properties中添加新的jpa属性,那么在我将该属性放入Properties对象之前不会注意到这种变化。那么,你知道这是否可能吗?问候!
【问题讨论】:
-
使用框架而不是围绕框架工作。基本上,您可以删除所有配置,因为 Spring Boot 会自动为您配置所有这些。基本上你想要的默认工作,但因为你已经解决了它不再工作的所有问题。
-
不要那样做,你应该使用相同的机制而不是绕过它。
-
不,您也可以使用 Spring Boot 进行测试(在 Spring Boot 参考指南中有说明)。你不需要不同的配置,如果你开始走这条路,你最终会在你的测试用例中使用 Spring Boot,那么你的测试用例的价值是什么?
-
您阅读过 Spring Boot 参考指南吗?这解释了如何重用现有配置来编写测试、集成测试或 Web 相关测试。
-
但是您在其他帖子中没有使用
@SpringApplicationConfiguration,而是@ContextConfiguration,所以它没有使用任何东西。此外,您还明确配置了 JPA,它也提供了。恕我直言,您试图通过解决问题而不是解决问题来解决问题。使用@SpringApplicationConfiguration并将其指向您的应用程序类。那么它应该一切正常。
标签: java spring jpa spring-boot spring-data-jpa