Spring MVC:xml和注释配置之间的问题

问题描述 投票:0回答:1

我创建了一个简单的控制器

@GetMapping("/playerAccount")
    public Iterable<PlayerAccount> getPlayerAccounts(com.querydsl.core.types.Predicate predicate) {
        return repository.findAll(predicate);
    }

[当我调用GET / playerAccount API时,出现异常IllegalStateException“找不到接口com.querydsl.core.types.Predicate的主要或默认构造函数”(由org.springframework.web.method.annotation.ModelAttributeMethodProcessor# createAttribute)。

经过一些(深入的研究!),我发现如果删除spring.xml文件中的以下行:

 <mvc:annotation-driven />

并且如果我在Spring.java文件中添加以下行:

@EnableWebMvc

然后问题消失了。

我真的不明白为什么。这可能是什么原因?我认为它们确实等效(一个是基于xml的配置,另一个是基于java / annotation的)。

我阅读了有关结合Java和Xml配置的this documentation,但那里没有相关的内容。


编辑:

从到目前为止得到的(很少)评论/答案中,我了解也许不是在我的API中使用谓词不是最佳选择。

尽管我真的很想了解错误的性质,但我首先要解决我要解决的最初问题:

假设我有一个MyEntity实体,该实体由10个不同的字段(具有不同的名称和类型)组成。我想轻松地搜索。如果我创建以下(空)界面:

public interface MyEntityRepository extends JpaRepository<MyEntity, Long>, QuerydslPredicateExecutor<MyEntity> {
}

然后没有任何其他代码(除了xml配置之外,我能够轻松地在数据库中搜索myEntity实体。

现在,我只想将该功能公开给Rest端点。理想情况下,如果我向MyEntity添加了新字段,则希望该API能像MyEntityRepository一样自动使用该新字段,而无需修改控制器。

我认为这是Spring Data的目的,也是一种好的方法,但是请告诉我是否有更好/更通用的方法为给定实体创建搜索API。

java spring spring-mvc spring-data-jpa spring-annotations
1个回答
-1
投票

我没有看到它返回异常,这就是为什么我认为这是一个依赖关系问题。尝试使您的代码看起来像这样,它将做到这一点。

@RestController
public class MyClass {

    @Autowired
    private final MyRepository repository;
    @GetMapping("/playerAccount")
    public Iterable<PlayerAccount> getPlayerAccounts() {
        return repository.findAll();
    }

如果请求中有参数,请添加@RequestParam。编码时间(yaaaaaay):

@RestController
public class MyClass {

    @Autowired
    private final MyRepository repository;
    @GetMapping("/playerAccount")
    public Iterable<PlayerAccount> getPlayerAccounts(@RequestParam(required = false) Long id) {
        return repository.findById(id);
    }

Ps:请求应保留相同的变量名,例如

.../playerAccount?id=6
© www.soinside.com 2019 - 2024. All rights reserved.