Spring Data REST - 没有为POST方法调用RepositoryEventHandler方法?

时间:2017-06-05 12:37:21

标签: java spring spring-boot spring-data spring-data-rest

我有以下域对象和DTO定义。

Country.java

@Data
@Entity
public class Country extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long countryID;

    @NotBlank(message = "Country name is a required field")
    private String countryName;

    private String countryNationality;
}

CountryDTO.java

@Data

public class CountryDTO {

    private List<Country> countries;
}

我已经在RepositoryRestController中覆盖了国家/地区类的POST方法。

@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }


}

现在我已经定义了一个RepositoryEventHandler来处理验证。

@Component
@RepositoryEventHandler
public class CountryHandler {


    @HandleBeforeCreate
    public void handleBeforeCreate(Country country) {

        System.out.println("testing");

}

但是当我向端点http://localhost:8080/countries发送POST请求时,不会调用eventhandler。我有什么问题吗?

更新1: 我使用Postman将以下JSON发送到端点。

"countries":[{
    "countryName":"Australia",
    "countryNationality":"Australian"

}]

3 个答案:

答案 0 :(得分:0)

很难为您提供一个不知道如何调用请求的确切解决方案。但可能的原因是您缺少斜杠符号@RequestMapping值属性:

@RequestMapping(method = POST, value = "countries")

应该是:

@RequestMapping(method = POST, value = "/countries")

答案 1 :(得分:0)

将AppConfigration中的Bean定义为

@Configuration
@EnableAsync
public class AppConfig {

  @Bean
    CountryHandler countryHandler (){
        return new CountryHandler ();
    }

}

它会起作用。

答案 2 :(得分:0)

尝试编辑Controller类注释:

&#xA;&#xA;
  @ RepositoryRestController&#xA;  
&#xA;&#xA ;

&#xA;&#xA;
  @ RestController&#xA;  
&#xA;&#xA;

主要是方法注释来自:

&#xA;&#xA;
  @RequestMapping(method = POST,value =“countries”)&#xA;  
&#xA ;&#xA;

&#xA;&#xA;
  @RequestMapping(value =“/ countries”,method = RequestMethod.POST,produce = MediaType.APPLICATION_JSON_VALUE)& #xA;  
&#xA;&#xA;

PS: produce = MediaType.APPLICATION_JSON_VALUE 如果您要返回json。

&# XA;