Using some beans in Filter bean class?

Anthony picture Anthony · Sep 5, 2010 · Viewed 28.2k times · Source

In my filter bean class, I added some beans dependency (with @Autowired annotation). But in the method doFilter(), all my dependency beans have null ...

public class FacebookOAuth implements Filter
{
@Autowired
private BusinessLogger logger;

@Autowired
private IUserSessionInfo userSessionInfo;

@Autowired
private FacebookOAuthHelper oAuthHelper;

public void init(FilterConfig fc) throws ServletException
{
    // Nothing to do
}

public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws   IOException, ServletException
{
    // HttpServletRequest req = (HttpServletRequest)sr;
    HttpServletResponse res = (HttpServletResponse) sr1;

    String code = sr.getParameter("code");

    if (StringUtil.isNotBlankStr(code))
    {
        String authURL = this.oAuthHelper.getAuthURL(code);

this.oAuthHelper is equal at null (and other dependancy beans to) ...

Could you help me ?


In fact I don't use MVC notion on server side (Spring). For my side client I use Flex technology and BlazeDS servlet ton communicate with my server.

So, that is the reason, I use the Filter bean notion.

So, how can I handle my session bean notion in my Filter bean ?


Skaffman,

I implemented your idea, so I update my application.xml with :

<bean id="FacebookOAuthHandler" class="com.xx.FacebookOAuthHandler" />
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
    <props>
       <prop key="/fbauth">FacebookOAuthHandler</prop>         
    </props>
   </property>
</bean>

and my FacebookOAuthHandler class :

public class FacebookOAuthHandler extends AbstractController
{
@Autowired
private BusinessLogger logger;

@Autowired
private IUserSessionInfo userSessionInfo;

@Autowired
private FacebookOAuthHelper oAuthHelper;

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // TODO

    return null;
}

But, this method handleRequestInternal is never called when my URL is : http://xx.xx.xx.xx/MyApp/fbauth

Answer

Mathias G. picture Mathias G. · Aug 13, 2015

I was facing the same problem and my first idea was to manually force Spring to apply @Autowired annotation to the filter like proposed here

http://forum.springsource.org/showthread.php?60983-Autowiring-the-servlet-filter

But I don't like the idea of hardcoding the bean name in my Java class.

I found an cleaner way that works as well:

public void init(FilterConfig filterConfig) throws ServletException {
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
            filterConfig.getServletContext());
}