Spring Data REST - RepositoryEventHandler方法没有被POST方法调用?
我有以下域对象和DTO定义。Spring Data REST - RepositoryEventHandler方法没有被POST方法调用?
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");
}
但是,当我发送POST请求到端点http://localhost:8080/countries
,该事件处理程序不被调用。有什么我做错了吗?
UPDATE 1: 我使用Postman将以下JSON发送到端点。
"countries":[{
"countryName":"Australia",
"countryNationality":"Australian"
}]
很难给你一个确切的解决方案,不知道你是如何调用请求。但是,可能的原因是你缺少斜杠符号@RequestMapping
值属性:
@RequestMapping(method = POST, value = "countries")
应该是:
@RequestMapping(method = POST, value = "/countries")
您可以使用注释询问您需要的信息 –
我已经更新了我发送给端点的JSON的问题 –
好吧,您是否尝试按照我的建议将斜杠放入RequestMapping值? –
在AppConfigration bean定义
@Configuration
@EnableAsync
public class AppConfig {
@Bean
CountryHandler countryHandler(){
return new CountryHandler();
}
}
它会对你有帮助。
这对我没有用。 –
尝试编辑也许Controller类注释来自:
@RepositoryRestController
到
@RestController
主要方法标注来源:
@RequestMapping(method = POST, value = "countries")
到
@RequestMapping(value = "/countries", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
PS:produces = MediaType.APPLICATION_JSON_VALUE
如果您要返回json。
如果我更改为@RestController,我的控制器类将超出Spring Data Rest范围,我将不得不实现GET,PUT和DELETE方法以及 –
我不这么认为。'打开声明org.springframework.web.bind.annotation.RestController'。你可以有'@ RestController'和'@RequestMapping(value =“/ countries”,method = RequestMethod.POST)'当然。我不确定通过实现另一个GET PUT DELETE方法是什么意思?对于休息控制器,我总是使用这两个注解的类和方法,我从来没有任何问题调用方法或其他。 (当然,当我们谈论Spring而不是'open declaration javax.ws.rs。*') –
我正在使用Spring Data Rest,因此实际上不需要实现控制器。 Spring在运行时会这样做。但是由于我使用的是DTO,我必须实现一个POST方法。 –
你如何在该URL上调用POST? – DaveRlz
我通过邮递员发送JSON –