我试图在我的代码中配置 promethues,我只需要创建一个如下所示的 bean。我想知道spring是如何识别CollectorRegistry的。 spring 如何实例化 CollectorRegistry 的所有必要变量并设置所有必要的配置?
@Component
public class TestProm{
public TestProm(CollectorRegistry registry){
// Some initialization code here
}
}
但是,当我尝试通过在我的 @Configuration
类中定义 @Bean
来以另一种方式定义它时,它似乎无法像我自己的那样正常工作CollectorRegistry
的构造函数没有所有必要的属性。
@Configuration
public class PromConfiguration{
@Bean
public TestProm getTestProm() {
return new TestProm(new CollectorRegistry());
}
}
public class TestProm{
public TestProm(CollectorRegistry registry){
//Some code here
}
}
当我执行自定义实现时,如何识别/复制 Spring 完成的 CollectorRegistry
初始化。
最佳答案
- How did spring instantiate all the necessary variable for CollectorRegistry and setup all the necessary cofnfiguration?
在第一个示例中,您需要 CollectorRegistry
类型的 Bean如果你有 spring-boot-starter-actuator
,Spring实际上会为你创建这样的bean和 Prometheus 依赖于您的类路径,并且您已启用自动配置:
- 如果您使用
@EnableAutoConfiguration
- 如果您使用 Spring Boot 和
@SpringBootApplication
注释(@EnableAutoConfiguration
是下面该注释的一部分):
...
@EnableAutoConfiguration
@ConfigurationPropertiesScan
...
public @interface SpringBootApplication
在这种情况下,Spring 将扫描类路径并加载所有配置。您感兴趣的 bean 属于 PrometheusMetricsExportAutoConfiguration
的一部分:
@Bean
@ConditionalOnMissingBean
public CollectorRegistry collectorRegistry() {
return new CollectorRegistry(true);
}
在第二个示例中 CollectorRegistry
的实例不受 Spring 管理,因为您通过 new
创建它关键词。但是它应该像 CollectorRegistry
一样工作。有默认构造函数来初始化 autoDescribe
字段至 false
。 Spring 创建的此类的默认 Bean(以上述方式)将此字段设置为 true
。所以这个字段的值就是你们差异的根源。
此外,如果这个实例不是由 Spring 管理的 - 它会阻止它被注入(inject)到需要它的其他组件中。范围为CollectorRegistry
是 Singleton(如上所示),其他 bean 可能需要共享实例才能正常工作(例如,某些 bean 可能想要注册/取消注册收集器),但如果您创建 CollectorRegistry
就像new
那样关键字 - 您不会获得单例实例,而是获得一个不能在其他 bean 之间共享的新实例。
- How do I recognise/replicate the initialization of CollectorRegistry done by spring when I do my custom implementation?
如果你想使用默认的CollectorRegistry
(假设您想使用按照上述方式默认创建的bean)只需将这种类型的bean注入(inject)到您的bean中就足够了。
关于java - spring如何识别构造函数中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58669279/