【问题标题】:Error while trying to inject ExampleMatcher尝试注入 ExampleMatcher 时出错
【发布时间】:2018-11-20 19:26:52
【问题描述】:

我正在使用Query by Example 来实现一些 我的 Spring Boot 应用程序中的复杂过滤器。

我使用ExampleMatcher 来定义必须如何处理字符串属性。所以我在几个需要过滤器的不同控制器中有一个类似于下面的代码:

  @GetMapping("/municipio/filter")
  public @ResponseBody ResponseEntity<?> filtro(
    Municipio municipio,
    Pageable page,
    PagedResourcesAssembler<Municipio> assembler
  ){

    ExampleMatcher matcher = ExampleMatcher.matching()
        .withIgnoreCase()
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);

    Example example = Example.of(municipio, matcher);
    Page<Municipio> municipios = this.municipioRepository.findAll(example, page);
    return ResponseEntity.ok(assembler.toResource(municipios));

  }

我想以集中方式定义 ExampleMatcher,以避免在每个控制器中复制此配置。所以我尝试将其定义为Bean 并以这种方式注入:

@Configuration
public class AppConfig {

  @Bean
  public ExampleMatcher getExampleMatcher() {
    return ExampleMatcher.matching()
        .withIgnoreCase()
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
  }
}

//Withing the controller class
@GetMapping("/municipio/filter")
public @ResponseBody ResponseEntity<?> filtro(
    Municipio municipio,
    Pageable page,
    PagedResourcesAssembler<Municipio> assembler,
    ExampleMatcher matcher //ExampleMatcher should be injected by Spring
  ){

    Example example = Example.of(municipio, matcher);
    Page<Municipio> municipios = this.municipioRepository.findAll(example, page);
    return ResponseEntity.ok(assembler.toResource(municipios));

  }

但我收到以下错误:

[未找到接口的主要或默认构造函数 org.springframework.data.domain.ExampleMatcher]: java.lang.IllegalStateException:没有主要或默认构造函数 找到接口 org.springframework.data.domain.ExampleMatcher

谁能指出我在这里缺少的东西?

【问题讨论】:

    标签: java spring spring-boot dependency-injection query-by-example


    【解决方案1】:

    ExampleMatcher 匹配器 不会作为控制器方法的参数注入,请参阅下面的代码,了解如何定义它:

    @Controller// or @RestController
    public class SomeController {
        @Autowired
        ExampleMatcher matcher;
        // rest of the code ...
    }
    

    并将其从参数列表中删除

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    相关资源
    最近更新 更多