找不到HATEOAS方法

时间:2014-08-17 19:15:52

标签: spring-boot spring-hateoas

我的控制器似乎无法找到像" linkTo"这样的HATEOAS方法。

我错过了什么吗?

的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>provider</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.5.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Security -->
        <!-- Auto configured, remove dependencies to disable. -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>

        <!-- OAuth 2.0 -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test-mvc</artifactId>
            <version>1.0.0.M2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <!-- Spring MongoDB -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
        </dependency>

        <!-- Spring REST MVC -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-webmvc</artifactId>
        </dependency>

        <!-- Dozer: DTO/Entity Mapper -->
        <dependency>
            <groupId>net.sf.dozer</groupId>
            <artifactId>dozer</artifactId>
            <version>5.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>

    </dependencies>

    <properties>
        <start-class>com.provider.core.Application</start-class>
    </properties>

    <build>
        <plugins>
            <plugin> 
                <artifactId>maven-compiler-plugin</artifactId> 
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/libs-snapshot</url>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/libs-snapshot</url>
            <snapshots><enabled>true</enabled></snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>

控制器

package com.provider.core;

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.provider.account.Account;
import com.provider.account.AccountDTO;

@Controller
public class AccountController
{
    private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
    @Autowired private AccountRepository repo;

    @RequestMapping(value = "account", method = RequestMethod.POST)
    public @ResponseBody HttpEntity<AccountDTO> createAccount(@RequestBody AccountDTO accountDto) {
        logger.info("Start createAccount()");
        Mapper mapper = new DozerBeanMapper();
        Account account = mapper.map(accountDto, Account.class);
        Account savedAccount = repo.save(account);
        AccountDTO savedAccountDto = mapper.map(savedAccount, AccountDTO.class);

        // DOES NOT COMPILE "linkto" not defined.
        savedAccountDto.add(linkTo(AccountController.class).slash(savedAccountDto.getId()).withSelfRel());

        return new ResponseEntity<AccountDTO>(savedAccountDto, HttpStatus.OK);
    }
}

8 个答案:

答案 0 :(得分:11)

如果您使用的是HATEOAS v1.0及更高版本(春季启动> = 2.2.0),请注意类名已更改。值得注意的是,以下类已重命名:

  • '''// Law report for // select b.bib_id as 'Bib ID', b.status as 'Bib Status', // b.created_by as 'Created by', // b.date_created as 'Date created', // b.updated_by as 'Updated by', // b.date_updated as 'Date updated', h.holdings_id as 'Holdings ID', h.location as 'Location', h.call_number as 'Call Number', i.updated_by as 'Updated by', i.date_updated as 'Date updated', n.note as 'Item note' from ole_ds_bib_t b join ole_ds_holdings_t h on b.bib_id = h.bib_id join ole_ds_item_t i on h.holdings_id = i.holdings_id join ole_ds_item_note_t n on i.item_id = n.item_id where h.location like '%Law%' and n.type = 'nonPublic' and n.note regexp '^[[:alpha:]]{6}$' and n.note not in ('folder', 'binder', 'SLAVEX', 'NISORI') and i.date_updated between '2019-11-01' and '2019-11-31';''' 更改为ResourceSupport
  • RepresentationModel更改为Resource
  • EntityModel更改为Resources
  • CollectionModel更改为PagedResources
  • PagedModel更改为ResourceAssembler

更多信息,请参见官方文档here

使用Spring boot starter时,以下依赖关系足以包含HATEOAS:

RepresentationModelAssembler

希望这些信息能帮助像我这样搜索了几个小时的人找到为什么<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency> 班没有得到解决的人。

答案 1 :(得分:5)

看起来您的POM缺少spring-hateoas依赖项。

首先将其添加到pom.xml:

<dependency>
    <groupId>org.springframework.hateoas</groupId>
    <artifactId>spring-hateoas</artifactId>
    <version>0.15.0.RELEASE</version>
</dependency>

然后你可以添加这个静态导入,你的代码应该编译:

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*

答案 2 :(得分:4)

如果您在日食中使用HATEOAS(版本:Oxygen.3a版本(4.7.3a)),请注意类名已更改。

Resource changed to EntityModel
Resources changed to CollectionModel

更多信息可在以下官方文档中找到->

https://docs.spring.io/spring-hateoas/docs/current/reference/html/

使用Spring boot starter时,必须使用以下依赖项来包括HATEOAS:

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-hateoas</artifactId>
 </dependency>

演示代码:

EntityModel<Users> resource = new EntityModel<Users>(user);
        ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());
        resource.add(linkTo.withRel("all-users"));

注意:您必须导入

import static org.springframework.hateoas.server.mvc.ControllerLinkBuilder.*;

希望此信息有助于查找为什么Resource类无法解决的原因!

答案 3 :(得分:2)

最新版本(2.2.0或>)中有一些术语更改。请参阅this document

答案 4 :(得分:1)

在pom.xml中添加以下依赖项,可以解决您的问题。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>

如果上述方法不起作用,则可以使用较早版本的hateos轻松解决问题。

由于Hateoas的新版本已完全更改,因此下面的链接可以为您提供帮助。 https://docs.spring.io/spring-hateoas/docs/current/reference/html/

我提到Hateoas方法的一些重大变化

ResourceSupport is now RepresentationModel

Resource is now EntityModel

Resources is now CollectionModel

PagedResources is now PagedModel

LinkDiscoverer API已移至客户端软件包。

LinkBuilder和EntityLinks API已移至服务器软件包。

ControllerLinkBuilder已移至server.mvc,已弃用,由WebMvcLinkBuilder代替。

RelProvider已重命名为LinkRelationProvider,并返回LinkRelation实例而不是字符串。

VndError已移至mediatype.vnderror包

答案 5 :(得分:0)

在我的情况下发生此问题,因为有两个Hateoas jars,一个具有资源接口,另一个具有具有相同groupId和arifactId的实现。 解决此问题-> 如果您使用的是4. *,请降级STS到3. * 如果您使用的是Spring Boot,请添加以下依赖项

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-hateoas</artifactId>
    </dependency>

添加此依赖项后,在存在pom.xml的命令提示符下的命令下运行

  1. mvn全新安装软件包
  2. mvn eclipse:eclipse

这一步为我解决了问题。

答案 6 :(得分:0)

如果有新人需要,我将把它留在这里:

ControllerLinkBuilder已过时,您应改用WebMvcLinkBuilder(选中此https://docs.spring.io/spring-hateoas/docs/1.0.0.M1/apidocs/org/springframework/hateoas/server/mvc/ControllerLinkBuilder.html

因此,如果:

import static org.springframework.hateoas.server.mvc.ControllerLinkBuilder.*;

使用此:

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;

答案 7 :(得分:0)

    Add following dependency :-

    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-hateoas</artifactId>
     <version>2.4.0</version>
    </dependency>
    
    Follow Sample Code :-
    import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
   
    @GetMapping(path = "/users/{id}")
    public EntityModel<User> getUserInfo(@PathVariable int id) {
        User user = userDao.getUser(id);
        
        EntityModel<User> entityModel = EntityModel.of(user);
        Link link = WebMvcLinkBuilder.linkTo(methodOn(this.getClass()).getUserList()).withRel("user-list");
        entityModel.add(link);
        
        if(user == null) {
            throw new UserNotFoundException("User not found with id : "+id);
        }
        return entityModel;
    }