开发者

Using some beans in Filter bean class?

开发者 https://www.devze.com 2023-01-14 06:44 出处:网络
In my filter bean class, I added some beans dependency (with @Autowired annotation). But in the method doFilter(), all my dependency beans开发者_如何学JAVA have null ...

In my filter bean class, I added some beans dependency (with @Autowired annotation). But in the method doFilter(), all my dependency beans开发者_如何学JAVA 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


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());
}


Assuming this Filter is wired up in your web.xml, then this isn't going to work, since it's not managed by Spring, it's managed by the servlet container. So things like autowiring won't work.

If you want to define a servlet filter as Spring bean, then you need to define it in the webapp's root application context (using a ContextLoaderListener in web.xml), and then defining a DelegatingFilterProxy which delegates to your Spring-managed bean to do the work.

However, do you really need a servlet filter for this? What what I know of Facebook auth stuff, this could be done just as easily with a Spring HandlerInterceptor. This would be considerably less configuration work than a delegating filter.


Look at this answer on site of spring: http://forum.springsource.org/showthread.php?60983-Autowiring-the-servlet-filter

In brief - you can manually force spring to apply @Autowire annotation to your filter:

public void init(FilterConfig filterConfig) throws ServletException {

    ServletContext servletContext = filterConfig.getServletContext();
    WebApplicationContext webApplicationContext = 
            WebApplicationContextUtils.getWebApplicationContext(servletContext);

    AutowireCapableBeanFactory autowireCapableBeanFactory =
           webApplicationContext.getAutowireCapableBeanFactory();

    autowireCapableBeanFactory.configureBean(this, BEAN_NAME);
}


I know it a now old question, but there is no example of usage of DelegatingFilterProxy in current responses, and one recent question asking for such an example was marked as a duplicate for this one.

So a DelegatingFilterProxy is a special filter that knows about root ApplicationContext and delegates its doFilterto a bean.

Example : MyFilter is a class implementing Filter, and myFilter is a spring bean

<bean id=myFilter class="org.example.MyFilter ...>...</bean>

or in a configuration class

@Bean
public MyFilter myFilter() {
    MyFilter myFilter = new MyFilter();
    //initialization ...
    return myFilter;
}

In web.xml, you just declare a DelegatingFilterProxy with same name as the bean :

<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

That way, as myBean is a true bean, it can be injected normally with other beans with @Autowired annotations, and its doFilter method will be called by the DelegatingFilterProxy. As you can use spring init and destroy methods, by default init and destroy methods will not be called, unless you specify the "targetFilterLifecycle" filter init-param as "true".


I was getting null pointer while accessing service class bean in filter class using Autowiring . I searched more than 100 links but not able to find solution. I am using spring Boot Application and configuration which is required to get bean in filter class :

FilterConfig.java which provides application context Object.

@Component
public class FilterConfig  implements ApplicationContextAware{

private static ApplicationContext context;


public static ApplicationContext getApplicationContext() {
       return context;
    }
public  static <T> T getBean(String name,Class<T> aClass){
    return context.getBean(name,aClass);
}

@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
    context = ctx;
}   

 }

in Filter class , I used this like :

 UserService userService =FilterConfig.getBean("UserService", UserService.class);

UserService this is bean name which is mentioned in

  @Service("UserService")
  public class UserServiceImpl implements UserService { ...}

No Configuration in main class of spring Boot :SpringBootServletInitializer

0

精彩评论

暂无评论...
验证码 换一张
取 消