3
votes

I am using spring boot with webflux and removed embedded tomcat dependency from starter web , I wanted to add base context path for my application , is there any way i can do ?? I need this because i have ingrees properties behind kubernetes cluster and redirection is made based on context path.

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
    <exclusion>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
    </exclusions>
1
You can find your answer hereMạnh Quyết Nguyễn
@Mạnh Quyết Nguyễn , I tried the same before posting a question but no luck :(prasannajoshi

1 Answers

3
votes

You cannot use spring web and spring webflux dependencies at the same time. If you do, spring will prioritize spring web and webflux filters will not be loaded at startup.

During startup spring tries to create the correct ApplicationContext for you. As written here Spring boot Web Environment if Spring MVC (web) is on the classpath, it will prioritize this context.

A spring boot application is either a traditional web application, OR it's a webflux application. It cannot be both.

ContextPath is not something that is used in reactive programming so you have to filter each request and rewrite the path on each request.

This should work, its a component webfilter that intercepts every request and then adds the context path that you define in application.properties

@Component
public class ContextFilter implements WebFilter {

    private ServerProperties serverProperties;

    @Autowired
    public ContextFilter(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        final String contextPath = serverProperties.getServlet().getContextPath();
        final ServerHttpRequest request = exchange.getRequest();
        if (!request.getURI().getPath().startsWith(contextPath)) {
            return chain.filter(
                    exchange.mutate()
                            .request(request.mutate()
                                            .contextPath(contextPath)
                                            .build())
                            .build());
        }
        return chain.filter(exchange);
    }
}

But this will only work if your application is loaded as a Spring reactive application.