bar*_*ini 22 java rest authorization spring-boot
我有一个用弹簧靴写的休息服务.我希望在启动后获得所有端点.我怎样才能实现这一目标?我的目的是,我希望在启动后将所有端点保存到数据库(如果它们尚不存在)并使用这些端点进行授权.这些条目将注入角色,角色将用于创建令牌.
小智 25
您可以在应用程序上下文的开头获取RequestMappingHandlerMapping.
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 */);
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者你也可以使用Spring引导执行器(你也可以使用actutator,即使你没有使用Spring引导),它会暴露另一个端点(映射端点),它列出了json中的所有端点.您可以点击此端点并解析json以获取端点列表.
kar*_* li 20
您需要 3 个步骤来公开所有端点:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
在 Spring Boot 2 中,Actuator 禁用了大多数端点,默认情况下只有 2 个可用:
/health
/info
Run Code Online (Sandbox Code Playgroud)
如果要启用所有端点,只需设置:
management.endpoints.web.exposure.include=*
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅:
https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html
顺便说一句,在 Spring Boot 2 中,Actuator 通过将其与应用程序 1 合并来简化其安全模型。
有关更多详细信息,请参阅这篇文章:
https://www.baeldung.com/spring-boot-actuators
Rev*_*ick 10
作为上述注释的补充,从Spring 4.2 开始,您可以使用这样的@EventListener
注释:
@Component
public class EndpointsListener {
private static final Logger LOGGER = LoggerFactory.getLogger(EndpointsListener.class);
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
applicationContext.getBean(RequestMappingHandlerMapping.class)
.getHandlerMethods().forEach((key, value) -> LOGGER.info("{} {}", key, value));
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想了解有关如何使用 Spring Events 和创建自定义事件的更多信息,请查看这篇文章:Spring Events
在 application.properties 中,我们需要 management.endpoints.web.exposure.include=mappings
然后我们可以看到所有的端点:http://localhost:8080/actuator/mappings
不要忘记将执行器添加到 POM。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20926 次 |
最近记录: |