【问题标题】:java springboot how to autowired in prometheusjava spring boot如何在prometheus中自动装配
【发布时间】:2019-11-27 17:45:27
【问题描述】:

我的 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 控制器

【问题讨论】:

  • 你用new创建了一个PrometheusMonitor吗?如果是这样,那么它是 stackoverflow.com/questions/19896870/… 的副本
  • 没有,因为 springboot 做到了,我关注了这个blog.autsoft.hu/…
  • 啊。好的。我现在看到了。如果对象尚不存在,您不能期望 Spring 自动装配对象的字段。由于您试图在构造函数中访问mydb,因此该对象尚未构造。停止使用现场注入。如果您发布实际代码而不是伪代码,一切都会更加清晰。
  • @JBNizet 那我该怎么办?
  • 停止使用场注入。使用构造函数注入。使用构造函数注入 mydb,就像注入注册表一样。

标签: java prometheus


【解决方案1】:

将@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/

【讨论】:

  • 我在 Danke dir 函数中缺少自动连线
【解决方案2】:

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

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;
   }
}

然后在您的课堂上,您可以执行以下操作:

@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 时自动装配参数的注册表

猜你喜欢
  • 1970-01-01
  • 2017-10-09
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 2019-10-21
  • 2019-05-03
  • 1970-01-01
  • 2016-10-03
相关资源
最近更新 更多