0

Is there a way to achieve the same result described here not depending on jersey but pure jax-rs? I'd like to create a Custom Injection Provider like Jersey so I can inject MyClass extracting custom data from HttpServletRequest

@Inject
protected MyClass myClass;

I also found this discussion useful, it works the same with java.util.function.Supplier but Jersey is still needed in this code:

bindFactory(MyFactoryOrSupplier.class)
.to(MyClass.class)
.in(RequestScoped.class);

EDIT:

CDI is also a good alternative, but pure jax-rs is preferable

RegRog
  • 373
  • 2
  • 12
  • `@Context` and `@Provider` as defined in jax-rs specs – maress Aug 03 '18 at 10:26
  • Can you elaborate a little more? – RegRog Aug 03 '18 at 15:08
  • There's [a hack using `@Path`](https://stackoverflow.com/a/23996225/2587435). Other than that, there is no pure JAX-RS way. JAX-RS doesn't specify any injection features, because it is part of Java EE, and Java EE already has CDI. Any solution (without CDI) will be implementation dependent. – Paul Samsotha Aug 03 '18 at 17:08
  • Ok, now I understand the situation. So, how could be a possible solution with CDI? – RegRog Aug 07 '18 at 09:47

1 Answers1

0

I find out this solution using CDI:

@ApplicationScoped
public class MyFactoryOrSupplier {

    @Produces
    @RequestScoped
    public IMyClass getMyClass(@Context HttpServletRequest request) {
        return (IMyClass) request.getAttribute("MyInjectedClass");
    }
}

and then in my servlets:

@Inject
protected IMyClass myClass;

beans.xml

bean-discovery-mode="annotated"

Actually MyClass implements IMyClass because I don't what MyClass to have a public constructor with no-args and this did the trick.

RegRog
  • 373
  • 2
  • 12