在名称为''的DispatcherServlet中找不到具有URI [/ api / transactions]的HTTP请求的映射

时间:2018-10-15 10:05:45

标签: spring-mvc spring-boot

我认为这是标准配置。但是我得到了404。我还应该在哪里配置Spring Boot?

@RestController
@RequestMapping("/api")
public class TransactionStatisticsController {

    public static final Logger logger = LoggerFactory.getLogger(TransactionStatisticsController.class);

    @RequestMapping(value = "/transactions",
                    method = RequestMethod.POST)
    public ResponseEntity sendTransaction(@RequestBody Transaction request) {
        logger.info( request.toString());
        return new ResponseEntity(HttpStatus.OK);
    }

}

这是我的测试。

@JsonTest
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class TransactionStatisticsRestTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private JacksonTester<Transaction> json;

    private static Transaction transaction;

    @BeforeClass
    public static void createTransaction(){
        BigDecimal amount = new BigDecimal(12.3343);
        transaction = new Transaction(amount.toString(),
                                      "2010-10-02T12:23:23Z");
    }

    @Test
    public void getTransactionStatus() throws Exception {

        final String transactionJson = json.write(transaction).getJson();
        mockMvc
                .perform(post("/api/transactions")
                .content(transactionJson)
                .contentType(APPLICATION_JSON_UTF8))
                .andExpect(status().isOk());
    }

    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsBytes(transaction);
    }
}

正在发出的请求是

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/transactions
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8]}
             Body = {"amount":"12.3343000000000007077005648170597851276397705078125","timestamp":"2010-10-02T12:23:23Z[UTC]"}
    Session Attrs = {}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
  

更新:我添加了一个指向基本软件包的组件扫描。我现在看不到该错误。请在有答案的地方查看评论。

4 个答案:

答案 0 :(得分:0)

这是因为@RequestMapping(value = "/transactions/", method = RequestMethod.POST)中的尾部冲突

将其删除,就可以了:value = "/transactions/" => value = "/transactions"

答案 1 :(得分:0)

似乎使用@JsonTest甚至不允许加载应用程序上下文,未加载结果映射并且抛出404,所以@JsonTest不能代替@SpringBootTest,这是一种方法轻松测试json serialization/de-serialization

根据文档:

  

您可以使用@JsonTest批注。 @JsonTest自动配置   可用的受支持的JSON映射器,可以是以下之一   库:

     
      
  1. Jackson ObjectMapper,任何@JsonComponent bean和任何Jackson模块
  2.   
  3. Gson
  4.   
  5. Jsonb
  6.   

如果使用Gson并删除@JsonTest,则测试运行正常。.(在pom中添加Gson依赖项)

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class DemoKj01ApplicationTests {

    @Autowired
    private MockMvc mockMvc;

    private static Transaction transaction;

    @BeforeClass
    public static void createTransaction(){
        BigDecimal amount = new BigDecimal(12.3343);
        transaction = new Transaction(amount.toString(),
                "2010-10-02T12:23:23Z");
    }

    @Test
    public void getTransactionStatus() throws Exception {

        //final String transactionJson = json.write(transaction).getJson();
        Gson gson = new Gson();
        String jsonRequest = gson.toJson(transaction);
        mockMvc
                .perform(post("/api/transactions")
                        .content(jsonRequest)
                        .contentType(APPLICATION_JSON_UTF8))
                .andExpect(status().isOk());
    }

答案 2 :(得分:0)

请分享您的项目文件夹架构。您的控制器程序包可能不在主类程序包中。这就是为什么它显示404。

此代码:

@RestController
@RequestMapping("/api")
public class TransactionStatisticsController {

    public static final Logger logger = LoggerFactory.getLogger(TransactionStatisticsController.class);

    @RequestMapping(value = "/transactions",
                    method = RequestMethod.POST)
    public ResponseEntity sendTransaction(@RequestBody Transaction request) {
        logger.info( request.toString());
        return new ResponseEntity(HttpStatus.OK);
    }

}

这应该放在您的主包中

@SpringBootApplication
public class YourApplication {

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

该主类驻留。

我希望这会有所帮助。

答案 3 :(得分:0)

如评论部分所述,仅要求绑定组件扫描基本程序包的位置。

  

@Component scan->配置要与@Configuration类一起使用的组件扫描指令。提供与Spring XML元素平行的支持。   可以指定basePackageClasses()或basePackages()(或其别名value())来定义要扫描的特定程序包。如果未定义特定的程序包,则将从声明此注释的类的程序包中进行扫描。