How to Get All Endpoints List After Startup, Spring Boot

…衆ロ難τιáo~ 提交于 2019-11-27 17:18:59

问题


I have a rest service written with spring boot. I want to get all endpoints after start up. How can i achieve that? Purpose of this, i want to save all endpoints to a db after start up (if they are not already exist) and use these for authorization. These entries will be inject into roles and roles will be used to create tokens.


回答1:


You can get RequestMappingHandlerMapping at the start of the application context.

public class EndpointsListener implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
            applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods().forEach(/*Write your code here */);
        }
    }
}

Alternately you can also Spring boot actuator(You can also use actutator even though you are not using Spring boot) which expose another endpoint(mappings endpoint) which lists all endpoints in json. You can hit this endpoint and parse the json to get the list of endpoints.

https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-endpoints




回答2:


You need 3 steps to exposure all endpoints:

  1. enable Spring Boot Actuator
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  1. enable endpoints

In Spring Boot 2, Actuator comes with most endpoints disabled, the only 2 available by default are :

/health
/info

If you want to enable all of the endpoints, just set:

management.endpoints.web.exposure.include=*

For more details, refer to:

https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html

  1. go!

http://host/actuator/mappings

btw, In Spring Boot 2, Actuator simplifies its security model by merging it with the application one.

For more details, refer to this article:

https://www.baeldung.com/spring-boot-actuators



来源:https://stackoverflow.com/questions/43541080/how-to-get-all-endpoints-list-after-startup-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!