java spring boot 如何在 prometheus 中自动装配

java springboot how to autowired in prometheus

我有一个用于我的 http url 的控制器,带有我的数据库的自动装配事件(一切正常)

@RestController public class CalculateDistance {

@Autowired MyDatabase mydb

some code

@GetMapping(value = "/url")
public Strng get() {
    return mydb.fetch("my query");
}

现在我有相同的自动装配但它不工作,我得到 null 而不是我的对象

 @Component public class PrometheusMonitor {

     @Autowired MyDatabase mydb

     public PrometheusMonitor(MeterRegistry registry) {
         meterRegistry = registry;

         mydb =  null ...

我得到一个异常,因为 mydb = null

但它适用于我的 http 控制器

首先确保您没有执行以下操作:

PrometheusMonitor monitor = new PrometheusMonitor(registry);

这不会 属性 自动装配您的数据库,如果您尝试自动装配 PrometheusMonitor 会给您错误,除非您为 MeterRegistry

创建了一个 bean

您可以执行以下操作

1) PrometheusMonitor

有一个无参数的构造函数
 @Component public class PrometheusMonitor {

   @Autowired MyDatabase mydb

   public PrometheusMonitor() {}

   public void initializeMonitor(MeterRegistry registry) {
     meterRegistry = registry;
   }
}

然后在您的 class 中,您可以执行以下操作:

@Service class MyService {
  @Autowire
  private PrometheusMonitor monitor;

  @PostConstruct
  privte void init() {
    MeterRegistry registry = getRegistry();
    monitor.initializeMonitor(registry);
  }
}

2) 为您的参数化构造函数创建一个 MeterRegistry Bean

@Bean
public MeterRegistry registry() {
   return getRegistry();
}

然后在创建 PrometheusMonitor 期间,它会在您自动装配 mintor 时自动装配参数的注册表

将@JB 所说的付诸实践,

构造函数注入将:

  • 支持不变性
  • 状态安全。对象被实例化为完整状态或根本未实例化。
  • 易于测试和模拟对象注入
  • 构造函数更适合强制依赖

IntelliJ IDEA 支持:

因此对于您的示例,您需要像这样在构造函数中传递它:

 @Component public class PrometheusMonitor {

 @Autowired
 public PrometheusMonitor(MeterRegistry registry, MyDatabase mydb) {
     meterRegistry = registry;

     assertNotNull(mydb);

     // rest of code

了解更多相关信息:

https://www.vojtechruzicka.com/field-dependency-injection-considered-harmful/