我有两个配置文件。一种用于构建(AppConfig),另一种用于测试(TestAppConfig)。

AppConfig:

@Configuration
@Import(HttpConfig.class)
@EnableTransactionManagement
@PropertySource(name = "props", value = { "file:app.properties" })
public class AppConfig {


TestAppConfig:

@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。

如果我进行构建,它将使用正确的属性正确运行。

最佳答案

有了详细信息,我认为问题可能就在这里

@ComponentScan(basePackages = "package")


在您的TestAppConfig类中。

如果您的AppConfig类位于该程序包中的某个位置,则进行组件扫描将为其创建一个bean(由于@Configuration),从而尝试加载无法找到的属性文件。使用您的@ComponentScan软件包更加明确/排他。

08-25 01:39