配置JUnit测试时,Spring自动装配环境为空

时间:2019-04-06 08:43:39

标签: spring junit properties configuration environment

我正在尝试使用Spring Java配置配置h2数据源以进行junit测试,并从外部文件加载属性。在遵循教程并使用@PropertySource并自动装配环境时,我发现在创建数据源时,环境为null。有人知道为什么在构建数据源bean时环境为null吗?

我创建了一个虚拟的Test类,其ContextConfiguration指向一个@Configuration类,在其中定义了数据库连接所需的bean。要创建这些文件,我只想使用一个外部属性文件,因此我使用了@PropertySource指向该文件,并使用了应使用这些属性填充的Environment。当我尝试访问任何Environment属性时,它会失败,因为Enviroment为null。

我还尝试创建一个PropertySourcePlaceHolder并使用@Value填充,但结果相同(该属性未填充)。

如果我的配置类实现了EnvironmentAware接口,则它有效地填充了我的数据源bean的环境,因此它可以正常工作。

我也进行了相同的测试,没有创建任何数据库Bean,而只是创建了一个虚拟Bean,该虚拟Bean在创建时仅打印环境属性,因此我发现了相同的问题(环境为空)。

我想应该有一些带有spring初始化顺序的东西,因为我不明白为什么它不起作用,因为所有示例都以我尝试的方式定义了bean。

//TEST CLASS
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {DataBaseTestConfiguration.class} , loader = AnnotationConfigContextLoader.class)
public class TestConfiguracion {
//Dummy
    @Test
    public void testPrueba(){
        assertEquals(1,1);
    }
}

我的配置类

//CONFIGURATION CLASS
@Configuration
@PropertySource("classpath:application-test.properties")
@EnableJpaRepositories(basePackages = "es.bla.springmvcexample")
@EnableTransactionManagement
public class DataBaseTestConfiguration {

  @Autowired
  private Environment environment;

  @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        System.out.println(environment); //<-- here is showing environment is null

        dataSource.setDriverClassName(environment.getProperty("jdbc.driverClassName")); //<-- Here fails
        dataSource.setUrl(environment.getProperty("jdbc.url"));
        dataSource.setUsername(environment.getProperty("jdbc.user"));
        dataSource.setPassword(environment.getProperty("jdbc.pass"));

        return dataSource;
    }

 ....

}

任何人都可以解释我为什么在创建bean时未注入环境?

编辑:我创建了另一个@Configuration(PropertiesConfiguration),在其中定义@PropertiesSource并更改@ContextConfiguration以添加该configurationClass。然后,我更改了DataBaseTestConfiguration并进行了注入@Enviroment的工作。 以相同的方式,在PropertiesConfiguration中添加虚拟Bean并尝试在该类中自动连接环境以填充该Bean会失败。就像我无法自动定义定义的Configuration类中的环境一样(但我不明白为什么定义类的问题很重要)

0 个答案:

没有答案
相关问题