Skip to main content
 首页 » 编程设计

java springboot 如何在普罗米修斯中 Autowiring

2023年09月11日58zhwl

我的 http url 有一个 Controller ,带有数据库的 Autowiring 事件(一切正常)

@RestController public class CalculateDistance { 
 
@Autowired MyDatabase mydb 
 
some code 
 
@GetMapping(value = "/url") 
public Strng get() { 
    return mydb.fetch("my query"); 
} 

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

 @Component public class PrometheusMonitor { 
 
     @Autowired MyDatabase mydb 
 
     public PrometheusMonitor(MeterRegistry registry) { 
         meterRegistry = registry; 
 
         mydb =  null ... 

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

但它适用于我的 http Controller

请您参考如下方法:

将@JB 所说的付诸实践,

构造函数注入(inject)将:

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

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/