Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java springboot如何在prometheus中自动连线_Java_Prometheus - Fatal编程技术网

java springboot如何在prometheus中自动连线

java springboot如何在prometheus中自动连线,java,prometheus,Java,Prometheus,我的http url有一个控制器,数据库有自动连线事件(一切正常) 现在我有相同的自动连线,但它不工作,我得到null而不是我的对象 @Component public class PrometheusMonitor { @Autowired MyDatabase mydb public PrometheusMonitor(MeterRegistry registry) { meterRegistry = registry; myd

我的http url有一个控制器,数据库有自动连线事件(一切正常)

现在我有相同的自动连线,但它不工作,我得到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;
   }
}
然后在课堂上,你可以做一些类似的事情:

@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创意支持:

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

 @Component public class PrometheusMonitor {

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

     assertNotNull(mydb);

     // rest of code
阅读更多关于此的信息:


您是否使用
new
创建PrometheusMonitor?如果是这样的话,那么它是no的复制品,因为springboot做了,我遵循了这个啊。好啊我现在看到了。如果对象还不存在,您不能期望Spring自动连接对象的字段。由于您试图在构造函数中访问
mydb
,因此对象尚未构造。停止使用现场注射。如果您发布的是实际代码,而不是伪代码,那么一切都会更加清晰。@JBNizet那么我应该怎么做?停止使用字段注入。使用构造函数注入。使用构造函数注入mydb,就像注入注册表一样。我缺少函数Danke dir的autowire
 @Component public class PrometheusMonitor {

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

     assertNotNull(mydb);

     // rest of code