title: May Spring @Bean methods return instance fields?
body: <p>The following Spring bean declaration appears to run and behave "as expected":</p>
  
  <pre class="lang-java prettyprint-override"><code>@Configuration
  public class AppConfig {
  
      private final Foo foo;
  
      public AppConfig() {
          foo = new Foo();
      }
  
      @Bean
      public Foo foo() {
          return foo;
      }
  }
  </code></pre>
  
  <p>where "as expected" means "nothing is <em>obviously</em> wrong".</p>
  
  <p>Supposing that <code>Foo</code> has some complex lifecycle (e.g. manages external resources with <code>AutoCloseable</code>), is that a valid and sensible declaration of <code>foo()</code>? All of the examples I can find, official and not, indicate that the <code>foo</code> instance should be instantiated inside <code>foo()</code>, not stored in and retrieved from a field. However, I can find no definitive information in any documentation that this should or should not be safe.</p>
  
  <p>The most relevant documentation I can find is about the Spring IoC bean lifecycle, for instance <a href="https://docs.spring.io/spring/docs/5.1.0.RELEASE/spring-framework-reference/core.html#beans-factory-scopes" rel="nofollow noreferrer">https://docs.spring.io/spring/docs/5.1.0.RELEASE/spring-framework-reference/core.html#beans-factory-scopes</a>. Reading between the lines, a <code>singleton</code> or <code>application</code> scoped bean, say, would be effectively valid because by the time it <em>ceases</em> to be valid the application is no longer alive. Since <code>singleton</code> is the default scope, the declaration above becomes implicitly valid.</p>
  
  <p>Even with the appropriate scoping, suppose you introduce an alternative, profile-specific declaration</p>
  
  <pre><code>@Bean("foo")
  @Profile("!test")
  public Foo realFoo() {
      return this.foo;
  }
  
  @Bean("foo")
  @Profile("test")
  public Foo testFoo() {
      return new TestFoo();
  }
  </code></pre>
  
  <p>Will <code>this.foo</code> now always be instantiated, even when activating the <code>test</code> profile? If so, does Spring still manage <code>realFoo()</code>'s value even though that bean is supposed to be inactive?</p>
  
  <p>This question is not a duplicate of <a href="https://stackoverflow.com/q/45183164/482758">Spring @Bean at method returning already created bean</a>, which <em>begs the question</em>, but that question <em>may</em> correctly identify the answer.</p>