2017-03-10 49 views
0

我有一個要求在運行時激活/停用(使用自定義執行器端點)的轉儲篩選器。但是我無法找到一種方法來重新啓動應用程序。我目前的解決方案做到了這一點:Java Spring - 在運行時添加和刪除篩選器

@Configuration 
public class AppConfigs { 

    @Value("${request.dumper.active:false}") 
    private Boolean dumpActive; 

    @Bean 
    public FilterRegistrationBean requestDumperFilter() { 
     FilterRegistrationBean registration = new FilterRegistrationBean(); 
     Filter requestDumperFilter = new RequestDumperFilter(); 
     registration.setFilter(requestDumperFilter); 
     registration.addUrlPatterns("/*"); 
     registration.setEnabled(dumpActive); 
     return registration; 
    } 

現在我想用這樣的事情:

@Component 
public class RequestdumperEndpoint implements Endpoint<Boolean > { 

    @Autowired 
    private RequestDumperFilter requestDumperFilter; 

    public String getId() { 
     return "requestdumper"; 
    } 

    public Boolean invoke() { 
     return requestDumperFilter.isEnabled(); 
    } 

    public Boolean setEnabled(Boolean enabled) { 
     return requestDumperFilter.setEnabled(enabled); 
    } 

但顯然有不的IsEnabled的setEnabled並在過濾器的方法。

任何想法如何能夠得到我需要的東西?

+0

上的東西[類似線(HTTP:/ /stackoverflow.com/a/6856036/1910582)可以有所幫助 –

回答

1

首先添加使用如豆的過濾器,你可以連接到它:

public class MyWebInitializer extends 
     AbstractAnnotationConfigDispatcherServletInitializer { 

    @Value("${request.dumper.active:false}") 
    private Boolean dumpActive; 

    @Bean 
    private MyRequestDumperFilter myRequestDumperFilter() { 
     MyRequestDumperFilter filter = new MyRequestDumperFilter(); 
     filter.setEnabled(dumpActive); 
     return filter; 
    } 

    @Override 
    protected String[] getServletMappings() { 
     //.. 
     return new String[0]; 
    } 

    @Override 
    protected Filter[] getServletFilters() { 
     return new Filter[]{myRequestDumperFilter()}; 
    } 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     //.. 
     return new Class<?>[0]; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     //.. 
     return new Class<?>[0]; 
    } 
} 

你過濾器,然後將看起來像:

public class MyRequestDumperFilter extends RequestDumperFilter{ 
     private Boolean enabled; 

     public void setEnabled(Boolean enabled) { 
      this.enabled = enabled; 
     } 

     public Boolean getEnabled() { 
      return enabled; 
     } 

     @Override 
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
      if (enabled) { 
       super.doFilter(request, response, chain); 
      } 
      else { 
       chain.doFilter(request,response); 
      } 
     } 
    }