0

我有两个配置文件。一种用于构建 (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。

如果我进行构建,它会以正确的属性正确运行。

4

1 回答 1

1

根据我们掌握的详细信息,我认为问题可能就在这里

@ComponentScan(basePackages = "package")

在你的TestAppConfig课上。

如果您的AppConfig类位于该包内的某个位置,则执行组件扫描将为它创建一个 bean(因为@Configuration),尝试加载它无法找到的属性文件。@ComponentScan对您的包裹更加具体/独特。

于 2013-10-01T18:30:25.340 回答