title: Configurable enum in Java
body: <p>I'm looking for a better pattern to implement something like this:</p>
  <pre><code>public static enum Foo {
      VAL1( new Bar() ),
      VAL2( new FooBar() );
  
      private final bar;
  
      private Foo( IBar bar ) {
          this.bar = bar;
      }
  
      public IBar getBar() { return bar; }
  }
  </code></pre>
  <p>The issue is that accessing the <code>enum</code> causes side effects. Say <code>Bar</code> opens a DB connection and the like. So even if I just need <code>VAL2</code>, I have to pay the price to setup <code>VAL1</code>.</p>
  <p>OTOH, the value of <code>bar</code> is tightly coupled to the <code>enum</code>. It's like an static attribute but <code>enum</code> has no lazy initialization. I could make <code>Foo.getBar()</code> abstract and use anonymous classes but then, I would have to pay the setup price every time.</p>
  <p>Is there a cheap way to add lazy init for attributes of <code>enum</code>s?</p>
  <p><strong>[EDIT]</strong> TO make this clear:</p>
  <ol>
  <li><p><code>getBar()</code> is called millions of times. It must be blinding fast.</p>
  </li>
  <li><p>We're talking singleton here (just like <code>enum</code> itself). Only a single instance must ever be created.</p>
  <p>For additional points, unit tests should be able to override this behavior.</p>
  </li>
  <li><p>Instances must be created lazily.</p>
  </li>
  </ol>
  <p>One solution we tried as to register the values as beans in Spring:</p>
  <pre><code>&lt;bean id=&quot;VAL1.bar&quot; class=&quot;....&quot; /&gt;
  </code></pre>
  <p>That allowed us to specify the values at runtime and override them in tests. Unfortunately, it means we have to inject the <code>ApplicationContext</code> into the <code>enum</code> somehow. So we need a global variable for that. <em>cringe</em></p>
  <p>What's worse: Looking up the value in <code>getBar()</code> is way too slow. We can <code>synchronize</code> <code>getBar()</code> and use <code>if(bar!= null)bar=context.get(name()+&quot;.bar&quot;);</code> to solve this.</p>
  <p>But is there a way without this that is as safe and fast as using the <code>enum</code> values themselves?</p>