1

What I'm trying to do is make a custom jersey @Context for my methods, exactly like this question, but in Scala.

Java way from the above post:

import javax.inject.Inject;
import javax.ws.rs.container.ContainerRequestContext;
import jetty.plugin.test.domain.MyObject;
import org.glassfish.hk2.api.Factory;

public class MyObjectFactory implements Factory<MyObject> {

    private final ContainerRequestContext context;

    @Inject
    public MyObjectFactory(ContainerRequestContext context) {
        this.context = context;
    }

    @Override
    public MyObject provide() {
        return (MyObject)context.getProperty("myObject");
    }

    @Override
    public void dispose(MyObject t) {}  
}

Attempting the Scala way:

class MyObjFactory(ctr: ContainerRequestContext) extends Factory[MyObj] {
  private final val context: ContainerRequestContext = ctr

  override def provide(): MyObj = context.getProperty("customObj").asInstanceOf[MyObj]

  override def dispose(obj: MyObj): Unit = { }
}

The problem here is I don't know where to put the @Inject annotation. My limited understanding of Scala is that everything in the class declaration is a constructor block, so I can't use @Inject to annotate the MyObjectFactory constructor method like in Java.

Am I just going about this all wrong?

Community
  • 1
  • 1
diplosaurus
  • 2,538
  • 5
  • 25
  • 53

1 Answers1

1

Annotations goes with the constructor:

import javax.inject.Inject

class MyObjFactory @Inject()(ctr: ContainerRequestContext) extends Factory[MyObj] {

  private final val context: ContainerRequestContext = ctr

  override def provide(): MyObj = context.getProperty("customObj").asInstanceOf[MyObj]

  override def dispose(obj: MyObj): Unit = {}

}
marcospereira
  • 12,045
  • 3
  • 46
  • 52