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
Release: 2023-05-19 17:04:06
forward
2265 people have browsed it

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()); 
  } 
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template