何时使用@EnableHypermediaSupport?

When to use @EnableHypermediaSupport?

根据Spring HATEOAS API,

Activates hypermedia support in the ApplicationContext. Will register infrastructure beans to support all appropriate web stacks based on selected HypermediaMappingInformation-type as well as the classpath.

我的 Spring 引导应用程序 (2.3.4) 具有以下依赖项:

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
implementation 'org.springframework.boot:spring-boot-starter-data-rest'

我的 SpringBootApplication class:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        
        // run this application as a Spring application        
        SpringApplication.run(MyApplication.class, args);
    }
}

我注意到我的存储库通过 Spring Data REST 返回 HALresponses 而没有使用 @EnableHypermediSupport 注释我的应用程序 class。什么时候需要这个注解?因为我正在使用 Spring Data REST,所以不需要它吗?

Spring 如果您的依赖项包含 spring-hateoas,启动已经自动为您配置。依赖项 spring-boot-starter-data-rest 包含 spring-hateoas.

文件 org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration@EnableHypermediaSupport(type = HypermediaType.HAL).


/**
 * {@link EnableAutoConfiguration Auto-configuration} for Spring HATEOAS's
 * {@link EnableHypermediaSupport @EnableHypermediaSupport}.
 *
 * @author Roy Clarkson
 * @author Oliver Gierke
 * @author Andy Wilkinson
 * @since 1.1.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ EntityModel.class, RequestMapping.class, RequestMappingHandlerAdapter.class, Plugin.class })
@ConditionalOnWebApplication
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class,
        HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class })
@EnableConfigurationProperties(HateoasProperties.class)
@Import(HypermediaHttpMessageConverterConfiguration.class)
public class HypermediaAutoConfiguration {

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnMissingBean(LinkDiscoverers.class)
    @ConditionalOnClass(ObjectMapper.class)
    @EnableHypermediaSupport(type = HypermediaType.HAL)
    protected static class HypermediaConfiguration {

    }

}

当然,您可以覆盖默认配置。

@Configuration
@EnableHypermediaSupport(…)
class MyHypermediaConfiguration { … }