In Spring Boot, you can invoke a specific filter per method by using the @WebFilter annotation with a specific URL pattern or by using the Filter interface with a specific condition. However, the most flexible way to achieve this is by using the @Bean annotation to define a filter and then using the FilterRegistrationBean to specify the URL patterns that the filter should apply to.
Here is an example of how you can invoke a specific filter per method in Spring Boot:
Method 1: Using @WebFilter annotation
java
@WebFilter(filterName = "myFilter", urlPatterns = "/api/myMethod")
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// Filter logic here
chain.doFilter(request, response);
}
}
In this example, the MyFilter filter will only be applied to the /api/myMethod endpoint.
Method 2: Using @Bean annotation
java
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean myFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/api/myMethod");
return registration;
}
}
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// Filter logic here
chain.doFilter(request, response);
}
}
In this example, the MyFilter filter will only be applied to the /api/myMethod endpoint.
Method 3: Using @Target annotation
You can also use the @Target annotation on a custom annotation to specify the methods that a filter should apply to.
java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyFilterAnnotation {
}
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// Filter logic here
chain.doFilter(request, response);
}
}
@RestController
public class MyController {
@MyFilterAnnotation
@GetMapping("/api/myMethod")
public String myMethod() {
return "Hello World!";
}
}
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean myFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public FilterInvocationSecurityMetadataSource securityMetadataSource() {
return new SecuredAnnotationSecurityMetadataSource();
}
public class SecuredAnnotationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
if (object instanceof FilterInvocation) {
FilterInvocation fi = (FilterInvocation) object;
if (fi.getRequestUrl().contains("/api/myMethod")) {
try {
Method method = MyController.class.getMethod("myMethod");
if (method.isAnnotationPresent(MyFilterAnnotation.class)) {
return Collections.singletonList(new SecurityConfig("MyFilter"));
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> clazz) {
return FilterInvocation.class.isAssignableFrom(clazz);
}
}
}
In this example, the MyFilter filter will only be applied to the myMethod endpoint in the MyController class if the method is annotated with the @MyFilterAnnotation annotation.
You can choose the method that best fits your needs.
The @Filters annotation in Java is part of the Java Servlet API, specifically the javax.servlet.annotation package.
Here's a brief overview of the @Filters annotation and its related classes:
@WebFilter (not @Filters): This annotation is used to declare a servlet filter. It can be applied to a class that implements the Filter interface. The @WebFilter annotation is used to define the filter's name, URL patterns, and other attributes.
@WebFilter("/myFilter")
public class MyFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
// Filter logic here
chain.doFilter(req, res);
}
}
code
* `@Filter`: This annotation is part of the Spring framework and is used to enable Spring's filter support. It can be applied to a Spring configuration class or a component.
```java
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
@Component
@Order(1)
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Filter logic here
chain.doFilter(request, response);
}
}
@Filters: This annotation is not a standard Java or Spring annotation. However, some frameworks like Jersey (a RESTful Web Services framework) use @Filters to define multiple filters for a resource.
@Provider
@PreMatching
public class MyFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Filter logic here
}
}
code
In Jersey, you can use the `@Filters` annotation to apply multiple filters to a resource.
```java
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
@RolesAllowed("admin")
@Filters(MyFilter.class)
public class MyResource {
// Resource methods here
}
In summary, the @Filters annotation is not a standard Java or Spring annotation but is used in some frameworks like Jersey to define multiple filters for a resource. The @WebFilter annotation is part of the Java Servlet API, and the @Filter annotation is part of the Spring framework.
“How to invoke only specific filter per method in springboot.” Conversation with llama-3.1-405b-instruct, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m8512vf3dz07cejrrxc147ha