尝试注入ExampleMatcher时出错

时间:2018-11-20 19:26:52

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

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

我使用ExampleMatcher定义必须如何处理String属性。因此,在需要过滤器的几个不同控制器中,我有一个类似于下面的代码:

  @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

有人可以指出我在这里想念的东西吗?

1 个答案:

答案 0 :(得分:0)

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

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

并将其从args列表中删除