title: Expression based Autowire in Spring Boot (with Kotlin)
body: <h1>Situation</h1>
  
  <p>I'm trying to come up with a methodology to conditionally load one bean (based on the existence of  2 property or environment variables) and if they are missing load up another bean.  </p>
  
  <h1>Vars</h1>
  
  <p>So the two property (or env vars) are:</p>
  
  <ul>
  <li><code>ProtocolHOST</code></li>
  <li><code>ProtocolPORT</code></li>
  </ul>
  
  <p>So for example <code>java -jar xxxx  -DProtocolHost=myMachine -DProtocolPort=3333</code> would use the bean I want, but if both are missing then you'd get another bean.</p>
  
  <pre><code>@Component("Protocol Enabled")
  class YesBean : ProtocolService {}
  
  @Component("Protocol Disabled")
  class NoBean : ProtocolService {
  </code></pre>
  
  <p>Later in my controller I have a:</p>
  
  <pre><code>@Autowired
  private lateinit var sdi : ProtocolService
  </code></pre>
  
  <p>So I've looked at a variety of options:</p>
  
  <p>using both <code>@ConditionalOnProperty</code> and <code>@ConditionalOnExpression</code> and I cant seem to make any headway.</p>
  
  <p>I'm pretty sure I need to go the <strong>Expression</strong> route so I wrote some test code that seems to be failing:</p>
  
  <pre><code>@PostConstruct
  fun customInit() {
      val sp = SpelExpressionParser()
      val e1 = sp.parseExpression("'\${ProtocolHost}'")
      println("${e1.valueType}   ${e1.value}")
      println(System.getProperty("ProtocolHost")
  }
  </code></pre>
  
  <p>Which returns:</p>
  
  <blockquote>
    <p>class java.lang.String   ${ProtocolHost} 
    taco</p>
  </blockquote>
  
  <p>So I'm not sure if my <strong>SPeL</strong> Parsing is working correctly because it looks like its just returning the string "${ProtocolHost}" instead of processing the correct value.  I'm assuming this is why all the attempts I've made in the Expression Language are failing - and thus why i'm stuck.</p>
  
  <p>Any assistance would be appreciated!</p>
  
  <p>Thanks</p>
  
  <h2>Update</h2>
  
  <p>I did get things working by doing the following</p>
  
  <p>in my main:</p>
  
  <pre><code> val protocolPort: String? = System.getProperty("ProtocolPort", System.getenv("ProtocolPort"))
   val protocolHost: String? = System.getProperty("ProtocolHost", System.getenv("ProtocolHost"))
  
   System.setProperty("use.protocol", (protocolHost != null &amp;&amp; protocolPort != null).toString())
   runApplication&lt;SddfBridgeApplication&gt;(*args)
  </code></pre>
  
  <p>And then on the bean definitions:</p>
  
  <pre><code>@ConditionalOnProperty(prefix = "use", name = arrayOf("protocol"), havingValue = "false", matchIfMissing = false)
  
  @ConditionalOnProperty(prefix = "use", name = arrayOf("protocol"), havingValue = "false", matchIfMissing = false)
  </code></pre>
  
  <p>However this feels like a hack and I'm hoping it could be done directly in SpEL instead of pre-settings vars a head of time.</p>