Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize auto-configured Spring Boot Bean

I am using Spring Boot, and largely just using the autoconfiguration options for most of the components. However, I have found a few instances where I just want slightly different behaviour from the Beans.

What is the best/suggested approach to doing this? In many cases I don't want to have to turn off autoconfig just to change one property on the bean, so hoping there is some way I can sensibly update beans properties?

The case I have is the DispatcherServlet - I am happy with the autoconfig but I just want to change my DispatcherServlet so the DispatchOptionsRequest is set to true. I am hoping I don't need to turn off autoconfig and copy the configuration locally just to call that setter method?

like image 788
rhinds Avatar asked Oct 19 '22 17:10

rhinds


1 Answers

The dispatcher servlet can be configured by declaring a bean of type DispatcherServlet named dispatcherServlet, then return an instance configured to your liking. This will override the previous declaration.

Example:

@Bean
public DispatcherServlet dispatcherServlet() {
    DispatcherServlet servlet = new DispatcherServlet();
    servlet.setDispatchOptionsRequest(true);
    return servlet;
}
like image 154
zrvan Avatar answered Oct 22 '22 07:10

zrvan