2017-06-05 49 views
1

我有以下域對象和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" 

}] 
+0

你如何在該URL上調用POST? – DaveRlz

+0

我通過郵遞員發送JSON –

回答

0

很難給你一個確切的解決方案,不知道你是如何調用請求。但是,可能的原因是你缺少斜槓符號@RequestMapping值屬性:

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

應該是:

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

您可以使用註釋詢問您需要的信息 –

+0

我已經更新了我發送給端點的JSON的問題 –

+0

好吧,您是否嘗試按照我的建議將斜槓放入RequestMapping值? –

0

在AppConfigration bean定義

@Configuration 
@EnableAsync 
public class AppConfig { 

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

} 

它會對你有幫助。

+0

這對我沒有用。 –

0

嘗試編輯也許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。

+0

如果我更改爲@RestController,我的控制器類將超出Spring Data Rest範圍,我將不得不實現GET,PUT和DELETE方法以及 –

+0

我不這麼認爲。'打開聲明org.springframework.web.bind.annotation.RestController'。你可以有'@ RestController'和'@RequestMapping(value =「/ countries」,method = RequestMethod.POST)'當然。我不確定通過實現另一個GET PUT DELETE方法是什麼意思?對於休息控制器,我總是使用這兩個註解的類和方法,我從來沒有任何問題調用方法或其他。 (當然,當我們談論Spring而不是'open declaration javax.ws.rs。*') –

+0

我正在使用Spring Data Rest,因此實際上不需要實現控制器。 Spring在運行時會這樣做。但是由於我使用的是DTO,我必須實現一個POST方法。 –

相關問題