Вызовите Spring PropertySourcesPlaceholderConfigurer с пользовательским параметром, таким как File

Поскольку SomeClass является изменяемым, вот один из способов сделать это:

[Fact]
public void UsingGeneratorOfDateTime()
{
    var fixture = new Fixture();
    var generator = fixture.Create>();
    var sut = fixture.Create();
    var seed = fixture.Create();

    sut.ExpirationDate =
        generator.First().AddYears(seed);
    sut.ValidFrom =
        generator.TakeWhile(dt => dt < sut.ExpirationDate).First();

    Assert.True(sut.ValidFrom < sut.ExpirationDate);
}

FWIW, используя AutoFixture с теориями данных xUnit.net , выше тест может быть записан как:

[Theory, AutoData]
public void UsingGeneratorOfDateTimeDeclaratively(
    Generator generator,
    SomeClass sut,
    int seed)
{
    sut.ExpirationDate =
        generator.First().AddYears(seed);
    sut.ValidFrom =
        generator.TakeWhile(dt => dt < sut.ExpirationDate).First();

    Assert.True(sut.ValidFrom < sut.ExpirationDate);
}

0
задан Sha 16 January 2019 в 11:02
поделиться

2 ответа

Проблема решена согласно комментарию @M. Deinum, как показано ниже:

@SpringBootApplication
@Slf4j
public class AppRunner implements CommandLineRunner {

    public static void main(String[] args) throws IOException {
        System.setProperty("spring.config.additional-location","path\\credentials.properties");
        SpringApplication.run(AppRunner.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        ...
    }
}

Или с использованием окружающей среды:

@Configuration
public class AppConfig  implements EnvironmentAware {

    Environment env;

    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws IOException {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        Properties properties = Utils.getProperties(new File(env.getProperty("credential")));
        properties.setProperty("startDate",env.getProperty("startDate"));
        propertySourcesPlaceholderConfigurer.setProperties(properties);
        propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
        propertySourcesPlaceholderConfigurer.setIgnoreResourceNotFound(true);
        return propertySourcesPlaceholderConfigurer;
    }

    @Override
    public void setEnvironment(Environment environment) {
        env = environment;
    }
}
0
ответ дан Sha 16 January 2019 в 11:02
поделиться

Каково ваше намерение использовать PropertySourcesPlaceholderConfigurer? Вы уже создали Бин, так что вы можете добавить его через @Autowired.

Метод с аннотацией @Bean вызывается через Spring при запуске приложения. Если вы хотите инициализировать этот компонент вручную, вы должны удалить аннотацию @Bean или создать компонент на основе файлов в своем классе AppConfig:

@Bean
public File getFile() {
    return new File("path\\credentials.properties");
}

РЕДАКТИРОВАТЬ:

Посмотрите на это напишите, если вы хотите использовать значения командной строки при создании bean-компонентов с аннотацией @Bean: Spring Boot: получить аргумент командной строки в аннотированном методе @Bean

0
ответ дан Maximus 16 January 2019 в 11:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: