FreeMarker configuration conflict (Spring Boot)



I have a FreeMarker configuration:

@Configuration
public class FreeMarkerConfig {

    @Bean
    public FreeMarkerConfigurationFactoryBean freeMarkerConfiguration() {
        FreeMarkerConfigurationFactoryBean freeMarkerConfigBean = new FreeMarkerConfigurationFactoryBean();
        freeMarkerConfigBean.setTemplateLoaderPath("/templates/");
        return freeMarkerConfigBean;
    }

}

And dependencies from build.gradle:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.retry:spring-retry:1.2.5.RELEASE'
    compile 'org.freemarker:freemarker:2.3.30'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    runtimeOnly 'org.postgresql:postgresql'

}

It works okay. But when I set following dependency in build.gradle:

implementation 'org.springframework.boot:spring-boot-starter-data-rest'

I’ll get an error:

The bean 'freeMarkerConfiguration', defined in class path resource 
[org/springframework/boot/autoconfigure/freemarker/FreeMarkerServletWebConfiguration.class], 
could not be registered. 
A bean with that name has already been defined in class path resource 
[com/lab/myservice/config/FreeMarkerConfig.class]

Seems like spring-data-rest provides configured FreeMarker too and conflict happens. @Primary and @Qualifier don’t work. What can I do?

[UPDATE]

Tried to add exclude to my main class:

@SpringBootApplication(exclude = {org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration.class})

Now application can start, but FreeMarker doesn’t work.

Answer

Found solutions:

  1. Set in properties (beans names should be the same): spring.main.allow-bean-definition-overriding=true

  2. Delete FreeMarker custom config and use default one. Set in properties: spring.freemarker.template-loader-path

And use

implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-freemarker'

Instead of spring-data-rest and org.freemarker:freemarker



Source: stackoverflow