Junior — Middle
How is the chain of handlers pattern implemented in Spring?
sobes.tech AI
Answer from AI
In Spring, the Chain of Responsibility pattern is implemented through a chain of handlers, for example, in the filter mechanism (FilterChain) or through a chain of handlers in Spring Security (FilterChainProxy). Each handler (filter) receives a request, processes it, and passes it on to the next in the chain. This allows for flexible addition, removal, or modification of handlers without changing their internal logic.
An example with filters in Spring MVC:
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// pre-processing
chain.doFilter(request, response); // passing to the next handler
// post-processing
}
}
Thus, each filter decides whether to pass the request further and can perform actions before and after passing. This is the implementation of the chain of responsibility.