FreeMarker 配置冲突(Spring 启动)

FreeMarker configuration conflict (Spring Boot)

我有一个 FreeMarker 配置:

@Configuration
public class FreeMarkerConfig {

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

}

以及来自 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'

}

它工作正常。但是当我在 build.gradle 中设置以下依赖项时:

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

我会得到一个错误:

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]

似乎 spring-data-rest 也提供了配置的 FreeMarker 并且发生了冲突。 @Primary 和@Qualifier 不起作用。 我能做什么?

[更新]

试图将 exclude 添加到我的主 class:

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

现在应用程序可以启动,但 FreeMarker 不工作。

找到的解决方案:

  1. 在properties中设置(bean名称要相同):spring.main.allow-bean-definition-overriding=true

  2. 删除 FreeMarker 自定义配置并使用默认配置。在属性中设置:spring.freemarker.template-loader-path

并使用

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

而不是 spring-data-restorg.freemarker:freemarker