title: Replace @Value property within @Configuration during Spring Boot test
body: <h1>Scenario</h1>
  
  <p>I've got a Spring Boot application with a <code>@Configuration</code> annotated Spring configuration class which contains some <code>@Value</code> annotated fields. For testing I want to replace these field values with custom test values.</p>
  
  <p>Unfortunately these test values cannot be overridden using a simple properties file, (String) constants or similar, instead I <strong>must</strong> use some custom written property resolving Java class (e.g. <code>TargetProperties.getProperty("some.username")</code>).</p>
  
  <p>The problem I have is that when I add a custom <code>PropertySource</code> to the <code>ConfigurableEnvironment</code> within my test configuration, it's already too late because this <code>PropertySource</code> will be added <strong>after</strong> the e.g. <code>RestTemplate</code> has been created.</p>
  
  <h1>Question</h1>
  
  <p>How can I override <code>@Value</code> annotated fields <em>within</em> a <code>@Configuration</code> class with properties obtained <em>programmatically</em> via custom Java code <em>before</em> anything else gets initialized?</p>
  
  <h1>Code</h1>
  
  <h2>Production Configuration Class</h2>
  
  <pre><code>@Configuration
  public class SomeConfiguration {
  
      @Value("${some.username}")
      private String someUsername;
  
      @Value("${some.password}")
      private String somePassword;
  
      @Bean
      public RestTemplate someRestTemplate() {
          RestTemplate restTemplate = new RestTemplate();
  
          restTemplate.getInterceptors().add(
              new BasicAuthorizationInterceptor(someUsername, somePassword));
  
          return restTemplate;
      }
  
  }
  </code></pre>
  
  <h2>Test Configuration Class</h2>
  
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
  public class SomeTest {
  
      @SpringBootConfiguration
      @Import({MySpringBootApp.class, SomeConfiguration.class})
      static class TestConfiguration {
  
          @Autowired
          private ConfigurableEnvironment configurableEnvironment;
  
          // This doesn't work:
  
          @Bean
          @Lazy(false)
          // I also tried a @PostConstruct method
          public TargetPropertiesPropertySource targetPropertiesPropertySource() {
              TargetPropertiesPropertySource customPropertySource =
                  new TargetPropertiesPropertySource();
              configurableEnvironment.getPropertySources().addFirst(customPropertySource);
              return customPropertySource;
          }
      }
  }
  </code></pre>