我有两个配置文件。一种用于构建 (AppConfig),一种用于测试 (TestAppConfig)。
应用配置:
@Configuration
@Import(HttpConfig.class)
@EnableTransactionManagement
@PropertySource(name = "props", value = { "file:app.properties" })
public class AppConfig {
测试应用配置:
@Configuration
@Import(HttpConfig.class)
@EnableJpaRepositories("repository")
@ComponentScan(basePackages = "package")
@EnableTransactionManagement
@PropertySource(name = "props", value = { "classpath:test_app.properties" })
public class TestAppConfig {
public static final String DB_NAME = "testdb";
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.addScript("import_test.sql").setName(DB_NAME).build();
}
@Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.setPersistenceUnitName(DB_NAME);
factory.setPackagesToScan("domain");
factory.setJpaVendorAdapter(jpaAdapter());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public JpaVendorAdapter jpaAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.HSQL);
return adapter;
}
@Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
@Bean
public HibernateExceptionTranslator exceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
HttpConfig 的完整性:
@Configuration
public class HttpConfig {
运行我的测试时注释如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestAppConfig.class)
public class MyTest {
我收到一个错误:
Failed to load bean class: TestAppConfig; nested exception is java.io.FileNotFoundException: app.properties (No such file or directory)
为什么它试图拉动 app.properties?我已经指定它使用 test_app.properties。
如果我进行构建,它会以正确的属性正确运行。