2017-06-27 50 views
2

我在玩Spring 5的功能,我在註冊RouterFunction時遇到了一些麻煩,它會被讀取,但不會被映射。 (在方法拋出異常嘗試。)如何在Spring Boot 2.0.0.M2的@Bean方法中註冊RouterFunction?

@Configuration 
@RequestMapping("/routes") 
public class Routes { 
    @Bean 
    public RouterFunction<ServerResponse> routingFunction() { 
    return RouterFunctions.route(RequestPredicates.path("/asd"), req -> ok().build()); 
    } 
} 

/routes/asd結果404,在我做錯了什麼線索? (我也試過沒有這個@RequestMapping/routes,它也返回404爲/asd

+0

的' RequestMapping'不應該影響'RouterFunction'映射。確定你的'Configuration'類被Spring組件掃描器挑選出來了嗎?請發佈有關您的項目結構和可能的'build.gradle' /'pom.xml'的更多信息。除了'RequestMapping',你的'RouterFunction'似乎很好 –

+0

我有一個簡單的主類,用'@SpringBootApplication'註解,它調用SpringApplication.run(TestfluxApplication.class,args); 另一個類是上面發佈的'Routes'類。 pom.xml使用spring-boot-starter-parent作爲父級;它具有spring-boot-starter-web和spring-boot-starter-webflux作爲依賴項。如果我用'@RestController'添加新類,它會被拾取,並且其中的映射被應用並可訪問。 –

+0

我扔例外此路由方法,沒有應用,以及堆棧跟蹤看起來是這樣的: https://pastebin.com/raw/44Bh7yv2 (所以我想它撿起) –

回答

2

我發現這個問題。

我有這些依賴都在我的pom.xml:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-web</artifactId> 
</dependency> 
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-webflux</artifactId> 
</dependency> 

取出彈簧引導啓動,網絡依賴,webflux開始正常工作。

另一種解決方案是保持網絡的依賴和排除的tomcat所以網狀開始工作:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-web</artifactId> 
    <exclusions> 
    <exclusion> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-tomcat</artifactId> 
    </exclusion> 
    </exclusions> 
</dependency> 
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-webflux</artifactId> 
</dependency> 
1

無需添加spring-boot-starter-web當你想使用Webflux,只需添加spring-boot-starter-webflux到項目的依賴。

對於您的代碼,刪除@RequestMapping("/routes")如果要使用純RouterFunction。而您的routingFunction bean沒有指定將使用哪種HTTP方法。

從我的github工作示例代碼:

@Bean 
public RouterFunction<ServerResponse> routes(PostHandler postController) { 
    return route(GET("/posts"), postController::all) 
     .andRoute(POST("/posts"), postController::create) 
     .andRoute(GET("/posts/{id}"), postController::get) 
     .andRoute(PUT("/posts/{id}"), postController::update) 
     .andRoute(DELETE("/posts/{id}"), postController::delete); 
} 

從檢查完整代碼:https://github.com/hantsy/spring-reactive-sample/tree/master/boot-routes

如果你堅持在傳統@RestController@RequestMapping,檢查另一個樣品:https://github.com/hantsy/spring-reactive-sample/tree/master/boot

相關問題