Home >Java >javaTutorial >How to solve the problem that springboot cannot reference non-static variables from a static context

How to solve the problem that springboot cannot reference non-static variables from a static context

WBOY
WBOYforward
2023-05-19 17:04:062246browse

Static methods can be called without creating an object, while non-static methods must have an instance of the object before they can be called.

Therefore, it is impossible to directly reference a non-static method in a static method, because it does not know which object's non-static method is called, and the compiler cannot give an answer because there is no object.

Java is afraid that it cannot find the object.

Solution:

spring’s set injection method, inject static variables through non-static setter methods, the example is as follows

@PropertySource(value = {"classpath:config/application.yml"},ignoreResourceNotFound = true,encoding="UTF-8") 
@Service 
public class tank_task {  
  private static String kafka;  
  public static String getProfilesKafka() { 
    return kafka; 
  }  
  @Value("${stream.kafka.servers}") 
  public void setProfilesKafka(String kafka) { 
    tank_task.kafka = kafka; 
  }  
  public static void tank_test(){  
    System.out.println("config static kafka :" + tank_task.getProfilesKafka()); 
  } 
}

The above is the detailed content of How to solve the problem that springboot cannot reference non-static variables from a static context. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete