Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI doesn't work in a simple adapter

I've added the CDI feature to the server.xml file<feature>cdi-1.2</feature>.

My maven module contains the beans.xml inside the <module_name>/src/main/resources/META-INF folder.

This is the beans.xml content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">
</beans>

But when I use the @Inject annotation it doesn't work, my bean is always null.

Code:

package ch.webapp.presentation;

...

@Path("/test/")
public class MyController {
    @Inject
    private MyService myService;

    @GET
    @Path("/foo/{count}")
    @OAuthSecurity(scope = "login")
    @Produces("application/json")
    public Response news(@PathParam("count") int count) {
        return Response
                .ok(myService.getBar(count))
                .build();
    }
}

EDIT:

That's my bean

package ch.webapp.service;

...

@RequestScoped
public class MyService {
    public String getBar(int count) {
        return "foo";
    }
}

I initialize jax-rs by extended the MFPJAXRSApplication class

package ch.webapp;

...

public class AccountApplication extends MFPJAXRSApplication {
    @Override
    protected void init() throws Exception {
    }

    @Override
    protected void destroy() throws Exception {
    }

    @Override
    protected String getPackageToScan() {
        return getClass().getPackage().getName();
    }
}

Environment details:

Launching mfp (WebSphere Application Server 8.5.5.8/wlp-1.0.11.cl50820151201-1942) on Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_172-b11 (en_CH)

Console Product version: 8.0.0.00-20180717-175523

What's wrong?

like image 933
Matteo Codogno Avatar asked Nov 27 '22 01:11

Matteo Codogno


1 Answers

First it seems that websphere jax-rs implementation does not integrate jax-rs resources automatically unless you annotate them appropriately.

Put the jax-rs in a CDI managed context by annotating it appropriately

@Path("/test/")
@javax.enterprise.context.RequestScoped
public class MyController {

    @Inject
    private MyService myService;

    @GET
    @Path("/foo/{count}")
    @OAuthSecurity(scope = "login")
    @Produces("application/json")
    public Response news(@PathParam("count") int count) {
        return Response
                .ok(myService.getBar(count))
                .build();
    }

}

Also be sure that the annotation used for your service is @javax.enterprise.context.RequestScoped

like image 120
maress Avatar answered Dec 23 '22 16:12

maress