Created
July 6, 2013 17:20
-
-
Save jpgreenwald/5940573 to your computer and use it in GitHub Desktop.
It seems to be impossible to use CDI within a JAX-RS 2.0 ContainerRequestFilter, but it is possible to first use a WebFilter to obtain the service and then pass it along via attributes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.swsandbox.resource; | |
import com.swsandbox.service.UserService; | |
import javax.inject.Inject; | |
import javax.servlet.*; | |
import javax.servlet.annotation.WebFilter; | |
import java.io.IOException; | |
@WebFilter(urlPatterns = "/*") | |
public class InjectionServlet implements Filter | |
{ | |
@Inject | |
UserService userService; | |
@Override | |
public void init(FilterConfig filterConfig) throws ServletException | |
{ | |
} | |
@Override | |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException | |
{ | |
request.setAttribute("userService", userService); | |
chain.doFilter(request, response); | |
} | |
@Override | |
public void destroy() | |
{ | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.swsandbox.resource; | |
import com.swsandbox.service.UserService; | |
import javax.annotation.Priority; | |
import javax.ws.rs.Priorities; | |
import javax.ws.rs.container.ContainerRequestContext; | |
import javax.ws.rs.container.ContainerRequestFilter; | |
import javax.ws.rs.ext.Provider; | |
import java.io.IOException; | |
@Priority(Priorities.AUTHENTICATION) | |
@Provider | |
public class MyFilter implements ContainerRequestFilter | |
{ | |
@Override | |
public void filter(ContainerRequestContext requestContext) throws IOException | |
{ | |
//Obtain a CDI injected object by name | |
UserService userService = (UserService) requestContext.getProperty("userService"); | |
} | |
} |
AWESOME! Thank you -- just what I needed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
perfect , well done