下面列出了org.springframework.web.servlet.function.ServerResponse#org.springframework.web.servlet.function.RouterFunction 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Detect a all {@linkplain RouterFunction router functions} in the
* current application context.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private void initRouterFunction() {
ApplicationContext applicationContext = obtainApplicationContext();
Map<String, RouterFunction> beans =
(this.detectHandlerFunctionsInAncestorContexts ?
BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RouterFunction.class) :
applicationContext.getBeansOfType(RouterFunction.class));
List<RouterFunction> routerFunctions = new ArrayList<>(beans.values());
if (!CollectionUtils.isEmpty(routerFunctions) && logger.isInfoEnabled()) {
routerFunctions.forEach(routerFunction -> logger.info("Mapped " + routerFunction));
}
this.routerFunction = routerFunctions.stream()
.reduce(RouterFunction::andOther)
.orElse(null);
}
@Override
public void initialize(GenericApplicationContext context) {
super.initialize(context);
this.dsl.accept(this);
context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(RouterFunction.class.getName(), context), RouterFunction.class, () ->
RouterFunctions.route().resources("/**", new ClassPathResource("static/")).build()
);
serverProperties.setPort(port);
serverProperties.getServlet().setRegisterDefaultServlet(false);
if (!convertersConfigured) {
new StringConverterInitializer().initialize(context);
new ResourceConverterInitializer().initialize(context);
}
if (context.containsBeanDefinition("webHandler")) {
throw new IllegalStateException("Only one webFlux per application is supported");
}
new ServletWebServerInitializer(serverProperties, webMvcProperties, resourceProperties).initialize(context);
}
@Bean
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
return route().add(pc.remainingProductRoutes(ps))
.before(req -> {
LOG.info("Found a route which matches " + req.uri()
.getPath());
return req;
})
.after((req, res) -> {
if (res.statusCode() == HttpStatus.OK) {
LOG.info("Finished processing request " + req.uri()
.getPath());
} else {
LOG.info("There was an error while processing request" + req.uri());
}
return res;
})
.onError(Throwable.class, (e, res) -> {
LOG.error("Fatal exception has occurred", e);
return status(HttpStatus.INTERNAL_SERVER_ERROR).build();
})
.build()
.and(route(RequestPredicates.all(), req -> notFound().build()));
}
/**
* Gets web mvc router function paths.
*
* @return the web mvc router function paths
*/
protected Optional<Map<String, AbstractRouterFunctionVisitor>> getWebMvcRouterFunctionPaths() {
Map<String, RouterFunction> routerBeans = applicationContext.getBeansOfType(RouterFunction.class);
if (CollectionUtils.isEmpty(routerBeans))
return Optional.empty();
Map<String, AbstractRouterFunctionVisitor> routerFunctionVisitorMap = new HashMap<>();
for (Map.Entry<String, RouterFunction> entry : routerBeans.entrySet()) {
RouterFunction routerFunction = entry.getValue();
RouterFunctionVisitor routerFunctionVisitor = new RouterFunctionVisitor();
routerFunction.accept(routerFunctionVisitor);
routerFunctionVisitorMap.put(entry.getKey(), routerFunctionVisitor);
}
return Optional.of(routerFunctionVisitorMap);
}
@Bean
@RouterOperations({ @RouterOperation(path = "/people", method = RequestMethod.GET, beanClass = PersonService.class, beanMethod = "all"),
@RouterOperation(path = "/people/{id}", beanClass = PersonService.class, beanMethod = "byId"),
@RouterOperation(path = "/people", method = RequestMethod.POST, beanClass = PersonService.class, beanMethod = "save") })
RouterFunction<ServerResponse> routes(PersonHandler ph) {
String root = "";
return route()
.GET(root + "/people", ph::handleGetAllPeople)
.GET(root + "/people/{id}", ph::handleGetPersonById)
.POST(root + "/people", ph::handlePostPerson)
.filter((serverRequest, handlerFunction) -> {
return handlerFunction.handle(serverRequest);
})
.build();
}
/**
* Configure routes via {@link RouterFunctions.Builder}.
* @see org.springframework.fu.jafu.BeanDefinitionDsl#bean(Class, BeanDefinitionCustomizer...)
*/
public WebMvcServerDsl router(Consumer<RouterFunctions.Builder> routerDsl) {
RouterFunctions.Builder builder = RouterFunctions.route();
context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(RouterFunction.class.getName(), context), RouterFunction.class, () -> {
routerDsl.accept(builder);
return builder.build();
});
return this;
}
public RouterFunction<ServerResponse> productSearch(ProductService ps) {
return route().nest(RequestPredicates.path("/product"), builder -> {
builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name"))))
.GET("/id/{id}", req -> ok().body(ps.findById(Integer.parseInt(req.pathVariable("id")))));
})
.onError(ProductService.ItemNotFoundException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
.status(HttpStatus.NOT_FOUND)
.build())
.build();
}
public RouterFunction<ServerResponse> adminFunctions(ProductService ps) {
return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class))))
.filter((req, next) -> authenticate(req) ? next.handle(req) : status(HttpStatus.UNAUTHORIZED).build())
.onError(IllegalArgumentException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
.status(HttpStatus.BAD_REQUEST)
.build())
.build();
}
@Override
public void unknown(RouterFunction<?> routerFunction) {
// Not yet needed
}
@Bean
public RouterFunction<?> userEndpoints() {
return route(GET("/"), request -> ok().body(findOne()));
}
@Bean
public RouterFunction<?> userEndpoints(Finder<Foo> entities) {
return route(GET("/"), request -> ok().body(entities.find(1L)));
}
@Bean
public RouterFunction<?> userEndpoints() {
return route().GET("/", request ->
ok().body(manager.find(Foo.class, 1L))).build();
}
public RouterFunction<ServerResponse> productListing(ProductService ps) {
return route().GET("/product", req -> ok().body(ps.findAll()))
.build();
}
public RouterFunction<ServerResponse> remainingProductRoutes(ProductService ps) {
return route().add(productSearch(ps))
.add(adminFunctions(ps))
.build();
}
@Bean
RouterFunction<ServerResponse> productListing(ProductController pc, ProductService ps) {
return pc.productListing(ps);
}
/**
* Create a {@code RouterFunctionMapping} with the given {@link RouterFunction}.
* <p>If this constructor is used, no application context detection will occur.
* @param routerFunction the router function to use for mapping
*/
public RouterFunctionMapping(RouterFunction<?> routerFunction) {
this.routerFunction = routerFunction;
}
/**
* Set the router function to map to.
* <p>If this property is used, no application context detection will occur.
*/
public void setRouterFunction(@Nullable RouterFunction<?> routerFunction) {
this.routerFunction = routerFunction;
}
/**
* Return the configured {@link RouterFunction}.
* <p><strong>Note:</strong> When router functions are detected from the
* ApplicationContext, this method may return {@code null} if invoked
* prior to {@link #afterPropertiesSet()}.
* @return the router function or {@code null}
*/
@Nullable
public RouterFunction<?> getRouterFunction() {
return this.routerFunction;
}