【问题标题】:Can Spring boot dynamically create end points based on the content of the property file?Spring boot 可以根据属性文件的内容动态创建端点吗?
【发布时间】:2016-12-28 10:28:25
【问题描述】:

到目前为止,我正在创建这样的端点:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public @ResponseBody String indexPost(HttpServletRequest request, HttpServletResponse response)
    throws Exception {
//Doing calculations
return "Result";
}

但我想在服务器启动时访问 application.properties,读取存储的数据,如下所示:

methods: {
"endpointOne": "DBStoredProcedure1",
"endpointTwo": "DBStoredProcedure2"
}

所以当我的 Spring Boot 应用程序启动时,它将基于属性文件创建所有 POST 端点,并使用第一个参数的名称(如“endpointOne”),并调用(并返回的结果)定义为第二个参数的存储过程(如“DBStoredProcedure1”)。

有可能吗?

【问题讨论】:

标签: java spring rest


【解决方案1】:

是的,你可以。与你现在尝试做的有点不同。

最好使用“PathVariable” - 您可以在此处找到详细信息:

https://spring.io/guides/tutorials/bookmarks/

http://javabeat.net/spring-mvc-requestparam-pathvariable/

您在 Controller 类中的方法如下所示:

 @RequestMapping(value="/{endPoint}", method=RequestMethod.POST)
public String endPoint(@PathVariable String endPoint) {
   //Your endPoint is now the one what the user would like to reach
   //So you check if your property file contains this String - better to cache it's content
   //If it does, you call the service with the regarding Stored Procedure.
   String sPName = prop.getSPName(endPoint); //You need to implement it.
   String answer = yourService.execute(sPName);
   return answer; 
 }

显然你需要实现一个方法来处理那些在属性文件中找不到的查询,但你明白了。

【讨论】:

  • 谢谢!!像魅力一样工作。
  • 介意举一个完整的例子吗?我是春天的新手。
  • 特别是如果端点不存在,您将如何引发 404?
【解决方案2】:

您可以使用通配符“/*”作为控制器中的值。这样您的所有端点都会使用相同的控制器请求方法。

下面是代码示例。

@RequestMapping(value = "/*", method = RequestMethod.GET, headers="Accept=*/*", produces = { "application/json" })
    public ResponseEntity<Object> getData(@RequestParam Map<String, String> reqParam, HttpServletRequest request)
            throws WriteException, IOException{

        MessageLogger.infoLog(EquityControllerImpl.class, GETQADTRSTOCKPRICELOGS,
                ENTRY);

        // Get Request URI
        MessageLogger.infoLog("Request URI: " + request.getRequestURI());
        String requestUri = request.getRequestURI();


        //Read all request parameters
        Map<String, String> requestParamMap = new HashMap<>();
        for (Map.Entry<String, String> param: reqParam.entrySet()
             ) {
            System.out.println("Parameter: " + param.getKey() + " ----> Value: " + param.getValue());
            requestParamMap.put(param.getKey(),param.getValue());
        }
}

您还可以定义静态 swagger.json 并在 swagger 配置中使用它。

    @Configuration
@EnableSwagger2
@Import(SpringDataRestConfiguration.class)
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.finance.dataplatform.*"))
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build().apiInfo(getApiInfo());
    }

    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder().title("Investment Management").build();
    }

    private static Predicate<String> matchPathRegex(final String... pathRegexs) {
        return new Predicate<String>() {
            @Override
            public boolean apply(String input) {
                for (String pathRegex : pathRegexs) {
                    if (input.matches(pathRegex)) {
                        return true;
                    }
                }
                return false;
            }
        };
    }

    @Bean
    WebMvcConfigurer configurer () {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addResourceHandlers (ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/config/swagger.json")
                        .addResourceLocations("classpath:/config");
            }
        };
    }


    @Primary
    @Bean
    public SwaggerResourcesProvider swaggerResourcesProvider(InMemorySwaggerResourcesProvider defaultResourcesProvider) {
        return () -> {
            SwaggerResource wsResource = new SwaggerResource();
            wsResource.setName("default");
            wsResource.setSwaggerVersion("2.0");
            wsResource.setLocation("/config/swagger.json");

            //List<SwaggerResource> resources = new ArrayList<>(defaultResourcesProvider.get());
            List<SwaggerResource> resources = new ArrayList<>();
            resources.add(wsResource);
            return resources;
        };
    }
}

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多