Spring @PropertySource从错误的@Configuration文件加载

时间:2013-10-01 18:19:15

标签: java spring

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

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

1 个答案:

答案 0 :(得分:1)

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

@ComponentScan(basePackages = "package")

在您的TestAppConfig课程中。

如果您的AppConfig类位于该包中的某个位置,则执行组件扫描将为其创建一个bean(因为@Configuration),尝试加载您找不到的属性文件。使用@ComponentScan个套件更具体/独家。