EJB injection in Glassfish webapp

I have an application that is trying to use the @EJB annotation to enter remote EJB links in my ejb.jar file. I get inconsistent results. In one case, I have a listener in web.xml that is called and, apparently, the EJB is loaded correctly, since I see that it connects to the EJB and calls the methods on it. In another class (struts2 action) I get an NPE when it tries to access an EJB link. As far as I can tell, they are identical calls in Java classes that live in the same .war file.

As a job, I added code in the constructor to search for EJBs by their global JNDI names, and it works great. I just can't understand why one @EJB works and not the other.

+3
source share
1 answer

How do you introduce EJB into Struts 2 actions? Do you use CDI? Are you using the Struts2 CDI plugin ?

Update: The problem is that the container does not create Struts, Struts is objects, so the container does not get the ability to inject anything. You will need to use the specified CDI plugin to include the attachment in your actions.

If you want to try, get Struts 2 sources:

svn co http://svn.apache.org/repos/asf/struts/struts2/trunk/ struts2

Then cdinto the directory struts2and run the following command (this will compile the necessary modules for struts-cdi-plugin)

mvn install -pl plugins -am

Then get the cdi-plugin sources:

svn co https://svn.apache.org/repos/asf/struts/sandbox/trunk/struts2-cdi-plugin/

And compile it:

mvn install

, pom.xml:

<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>2.2.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-cdi-plugin</artifactId>
    <version>2.2.0-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>javassist</groupId>
  <artifactId>javassist</artifactId>
  <version>3.8.0.GA</version>
</dependency>

EJB, Action:

public class HelloWorld extends ActionSupport {

    @Inject
    HelloEJB helloEjb;

    @Override
    public String execute() throws Exception {
        setMessage(helloEjb.getMessage());
        return SUCCESS;
    }

    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

}

. https://svn.apache.org/repos/asf/struts/sandbox/trunk/struts2-cdi-example/ .

+3

Source: https://habr.com/ru/post/1746048/


All Articles