title: Lazy object builders with Spring bean
body: <p>I am playing with an idea to use a similar approach that <code>@Configuration</code> classes are able to do, that they can lazily create beans with calls to <code>@Bean</code> methods and return the existing objects if already called. This is done through some magic with CGLib proxies.</p>
  
  <p><strong>One particular interesting thing is that it works even when calling the method on itself:</strong></p>
  
  <pre><code>@Configuration
  class Config {
      @Bean ClassA beanA() {
          return new ClassA(beanB());
      }
  
      @Bean ClassB beanB() {
          return new ClassB();
      }
  }
  </code></pre>
  
  <p>Now, in my use case, not concerning Spring configuration, I want to use this ability to lazily create arbitrary object graphs (which should not be Spring Beans) by calling a method of a <em>Builder bean</em> that would create the objects if not yet called, and returning existing objects if already called. And as well I want to leverage the ability to self-invoke methods on the same instance. So far, I wasn't able to do this.</p>
  
  <p>How can I create and enhance Spring Beans (as CGLib proxies) <strong>so that they are able to self-invoke methods</strong>, similarly the <code>@Configuration</code> classes do, but with my own custom advice handling the laziness and caching?</p>
  
  <hr>
  
  <p><strong>EDIT : more detail</strong></p>
  
  <p>The result, in the end, should look similar to the configuration example above, but it would be a normal Spring singleton bean:</p>
  
  <pre><code>@Component
  @MyBuilder // or some other custom annotation
  class MyObjectGraphBuilder {
      @Builder ClassA objectA() {
          return new ClassA(objectB());
      }
  
      @Builder ClassB objectB() {
          return new ClassB();
      }
  }
  </code></pre>
  
  <p>With the added capability to only call the original method once, and caching the result for any subsequent call (<strong>including especially the self-invocation</strong>). The above is just an example, there may be many such builder beans, and they can be complex with cross-dependencies between them.</p>
  
  <p><em>The method call result caching is simple (could be done by AOP), but what I want is the self-invocation capability, which is normally not supported by Spring unless it's a <code>@Configuration</code> class.</em></p>
  
  <p>I figured that Spring is doing this by enhancing the <code>@Configuration</code> bean classes with their own CGlib proxies. However, it involves a lot of copying and customizing (e.g. ConfigurationClassEnhancer, ConfigurationClassPostProcessor, etc), and so far I had no luck of actually making it work with my custom Post Processor and Enhancer (the code is too long, but it's basically a copy of the mentioned classes and writing my custom method interceptors). So I'm trying to find if there exists any other way.</p>