使用自定义Gson覆盖Spring-Boot的GsonAutoConfiguration

时间:2017-03-13 17:54:51

标签: spring-boot jersey gson

有没有办法在spring-boot中覆盖GsonAutoConfiguration?

我想在gson实例中添加一些typeAdapter。

最好使用java配置

我已将以下内容添加到application.properties中。 spring.http.converters.preferred-json-mapper=gson

和以下课程

@Configuration
@ConditionalOnClass(Gson.class)
public class GsonConfig {
    @Bean
    public Gson gson() {
        return new GsonBuilder()
            .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
            .setPrettyPrinting().create();
    }
}

我也在混音中使用泽西岛。 所以我也有以下代码,这些代码也没有用。

InternalApplication.java

import com.google.gson.GsonBuilder;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.immutables.gson.stream.GsonMessageBodyProvider;
import org.immutables.gson.stream.GsonProviderOptionsBuilder;
import org.joda.time.DateTime;

public class InternalApplication extends Application {

  @Override
  public Set<Class<?>> getClasses() {
    final Set<Class<?>> classes = new HashSet<>();
    classes.add(TestResource.class);
    return classes;
  }

  @Override
  public Set<Object> getSingletons() {
    final Set<Object> singletons = new HashSet<>();
    singletons.add(new GsonMessageBodyProvider(
            new GsonProviderOptionsBuilder()
                .gson(new GsonBuilder()
                    .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
                    .setPrettyPrinting()
                    .create())
                .lenient(true)
                .build()
        )
    );
    return singletons;
  }
}

1 个答案:

答案 0 :(得分:3)

从什么时候Gson在Spring Boot中与Jersey有什么关系?它没有。你真正想要做的是首先禁用杰克逊(这是默认的提供者)。然后,您可以注册GsonMessageBodyProvider

基本上你需要做的就是将杰克逊提供程序从你的Maven / Gradle依赖项中排除,因为泽西启动程序将其拉入

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jersey</artifactId>
  <exclusions>
    <exclusion>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </exclusion>
    <exclusion>
      <groupId>org.glassfish.jersey.media</groupId>
      <artifactId>jersey-media-json-jackson</artifactId>
    </exclusion>
  </exclusions>
</dependency>

而且我不太确定你为什么使用Application类,因为Spring Boot不支持它的自动配置。您应该使用ResourceConfig

@Component
@ApplicationPath("/api")
public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
        register(TestResource.class);
        register(new GsonMessageBodyProvider(...));
    }
}