Fabian Förster
Fabian Förster

Reputation: 11

Java EE 5 / Servlet 2.5 inject EJB into ServletFilter

I want to inject session beans into my ServletFilter, which seems not to work. Can you please tell me how to achieve this?

public class MyExample implements Filter {
    @EJB
    private MyBean someEjb;

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                     FilterChain filterChain) throws IOException, ServletException{
        someEjb.toString();
    }
}

Results in NullPointerException because myEjb is null. The platform used is JBoss 5.1 MyBean can be accessed correctly from other EJBs or from Servlets.

Thank you.


Problem Solved (though I do not know why):

The application consists of three artifacts: - A jar containing the EJBs - A war containing servlets - An ear containing both the above

If i package the Filter in the jar, the problem occurs. If i package it along with the servlets in the war, the problem does not occur.

So, immediate problem solved but not understood.

Maybe someone can help me understand that?

Upvotes: 1

Views: 3094

Answers (2)

Victor Gimeno
Victor Gimeno

Reputation: 11

We faced a similar problem, we had some @WebFilter and @WebListener components packaged inside a Jar that weren´t readed (the annotations weren´t processed).

The objetive was to tell the container to scan other jars looking for other annotated components.

We achive the goal adding the attribute metadata-complete to web.xml declaration. Example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app  version="3.0" 
          xmlns="http://java.sun.com/xml/ns/javaee" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
          metadata-complete="false">
  
  ...NORMAL_CONTENT_HERE...
  
</web-app>

Hope it helps.

Upvotes: 1

Adeel Ansari
Adeel Ansari

Reputation: 39907

If both the servlet and EJB are not in a single ear file, one must use @EJB(mappedName="name") while injecting EJB. Check this post for more details.

Related links: Injection from outside modules

Of course, Filter is a kinda Servlet, therefore known as "Servlet Filter". And both Servlet and Filter are web component, hence belongs to web archive, .war, not Java archive, .jar. Filter in jar will not be scanned to inject that kinda annotations and will be dealt as any other regular Java class.

Upvotes: 3

Related Questions