Search code examples
javaspringspring-bootannotationsservlet-filters

How can I run servlet-filter of a different project in my project without spring @Component or @Bean annotation


I am working with a usecase where there is a project containing servlet-filter acting as a middleware. To run this filter, i am putting @Component on the servlet-filter class. And in my another application i put the package containing this filter like below.

Project A (which acts as a middleware)


package com.filter_demo;
.
.
.

@Component
public class middleware extends HttpFilter {

@Override
public void init(FilterConfig filterConfig) {
   System.out.println("Inside init of filter");
}

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain){

System.out.println("incoming request");

filterChain.doFilter(request,response);

System.out.println("outgoing response");
}

@Override
public void destroy(){

}
}

Project B (containing actual application logic, controller etc)

package com.demoApp;
.
.
.
@SpringBootApplication(scanBasePackages = {"com.demoApp","com.filter_demo"})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Note: If i don't put @Component on the filter class then the http request doesn't come to this filter.

How can i use this filter without adding @Component on it, basically making it independent of spring so that i can use this filter in my core-java non-springboot application which uses servlets, jsp, etc.

And i don't want to make major changes in the Project B ( my application ) to register that filter.


Solution

  • To replace @Component annotation from "Middleware"/filter, this is sufficient/equivalent:

    @SpringBootApplication(scanBasePackages = {"com.demoApp","com.filter_demo"})// or any "visible configuration"
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
        @Bean // !
        public middleware middleware(/*...*/) {
           return new middleware(/*...*/);
        }
    }
    

    ...to make the filter "spring independent", you should also ensure, that it uses no other [import] org.springfr...*.

    In your target (non-spring) e.g. web.xml application, you would configure it like:

    <filter> 
        <filter-name>myMiddleware</filter-name> 
           <filter-class>com.filter_demo.middleware</filter-class> 
          <!-- init-param>
            <param-name>foo</param-name>
            <param-value>bar</param-value>
          </init-param-->
        </filter> 
        <filter-mapping> 
           <filter-name>myMiddleware</filter-name> 
           <url-pattern>/foo/bar/*</url-pattern> 
        </filter-mapping>
    </filter>