Spring Boot: Overriding favicon

梦想的初衷 提交于 2019-11-27 18:26:34
Dave Syer

You can just put your own favicon.ico in the root of the classpath or in any of the static resource locations (e.g. classpath:/static). You can also disable favicon resolution completely with a single flag spring.mvc.favicon.enabled=false.

Or to take complete control you can add a HandlerMapping (just copy the one from Boot and give it a higher priority), e.g.

@Configuration
public static class FaviconConfiguration {

@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(Integer.MIN_VALUE);
    mapping.setUrlMap(Collections.singletonMap("mylocation/favicon.ico",
            faviconRequestHandler()));
    return mapping;
}

@Bean
protected ResourceHttpRequestHandler faviconRequestHandler() {
    ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
    requestHandler.setLocations(Arrays
            .<Resource> asList(new ClassPathResource("/")));
    return requestHandler;
}
}
Ross

None of this was necessary for me.

Why override the default when you can bundle a resource with the generated JAR that will take higher precedence than the default one.

To achieve a custom favicon.ico file, I created a src/main/resources directory for my application and then copied the favicon.ico file into there. The files in this resources directory are moved to the root of the compiled JAR and therefore your custom favicon.ico is found before the Spring provided one.

Doing the above achieved the same effect as your updated solution above.

Note that since v1.2.0 you can also put the file in src/main/resources/static.

I really like Springboot because overall it is full of smart solutions but I refuse to register an application bean to provide a favicon because that is just plain stupid.

I just added my own favicon link in my html page head like so.

<link rel="icon" type="image/png" href="images/fav.png">

Then I renamed my favicon and placed it at

<ProjFolder>/src/main/resources/static/images/fav.png

Now I have an icon in Chrome and Firefox browser tabs and the Safari address bar without having to use Spring and Java, and I should not have to chase changes to Springboot in newer versions for such trivial functionality.

Since Spring Boot 1.2.2 and 1.1.11 you can easily disable default favicon using spring.mvc.favicon.enabled = false property.

For more informations visit:

Newer versions of Boot (1.2 for sure but maybe also 1.1.8) allow you to just put a favicon.ico in your static resources.

registry.addResourceHandler("/robots.txt").addResourceLocations("/");

registry.addResourceHandler("/favicon.ico").addResourceLocations("/");

robots.txt, favicon.ico file location : /src/main/resources

i used spring boot 1.2.1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!