title: How to do JEE EJB Dependency Injection with Kotlin
body: <p>I have converted a REST resource in a JEE application formally written in Java to Kotlin. The application runs in a Wildfly Application Server with Weld as Dependency Injection framework.</p>
  
  <p>This is the final implementation I came up with:</p>
  
  <pre><code>@Path("/myResource")
  open class MyResource {
  
    @Context
    private lateinit var context: SecurityContext
  
    open protected setSecurityContext(securityContext: SecurityContext) {
      this.context = securityContext
    }
  
    @POST
    @Path("/change")
    @Transactional
    @Consumes(MediaType.APPLICATION_JSON)
    open internal fun change(data: MyChangeData, @Context uriInfo: UriInfo): Response {
      // ...
    }
  }
  </code></pre>
  
  <p>The setter is for testing purposes. With Mockito or other mocking frameworks that can set private fields this is not neccessary.</p>
  
  <p>I had some issues with this implementation:</p>
  
  <ol>
  <li>I had to change the class and all methods to <code>open</code> to allow the CDI Container to create a proxy for this bean. As I understand this topic there is no other way to allow Weld to do its work without allowing subclassing?</li>
  <li>Generally Kotlin generates setters and getters for properties with the given modifier (public/private/protected) backed by a private field. But when using <code>lateinit</code> the field is generated with the same visibility as the getters and setters (Kotlin in Action, p. 146). I don't understand the background for this special behaviour. Using <code>public</code> property causes an error in Weld reporting that public fields are not allowed. How can I declare that the field should be private but the getter and setter is protected (to initialize the Resource in tests)?</li>
  <li>What is annotated in the code above? The field or the generated methods? If it is the field: How can I annotate the setter only?</li>
  <li>Because all methods but private ones have to be <code>open</code> all properties but private ones are rejected by the Weld container: Kotlin creates Getters and Setters with the same visibility and the container tries to proxy the bean proxying all methods for the bean. This does not work because the generated getters and setters are not <code>open</code>. For private properties there simply is no problem because the container does not proxy private methods. As I see there is no possibility to declare a getter/setter as <code>open</code> therefor it is not possible to use protected properties</li>
  </ol>
  
  <p>EDIT: Added Ploblem 4 and changed the Implementation because of this problem to private with a setter.</p>