calling non static method from static class in java with spring autowiring?

ⅰ亾dé卋堺 提交于 2021-02-07 21:52:17

问题


I have below interface and its implementation class.

Demo.java

public interface Demo{

 void showDemo();

}

DemoImpl.java

@Service
public class DemoImpl implements Demo{

  public void showDemo(){

       //To Do

    }

}

Now i have one class with static method which will internally call showDemo() as below.

DemoStatic.java

@Component
public class DemoStatic{

 @Autowired
 private Demo demo;



     public static void callShowDemo(){

       demo.showDemo(); //calling non static method from static method

       }

}

Here i am calling non static method from static method. Is my design correct? Or do i need to change my design? Please suggest me.

Thanks!


回答1:


No your design is not correct.

private Demo demo;

has to be

private static Demo demo;

You just cant use NON static members in a static method




回答2:


You can do it this way

@Component
public class DemoStatic {

 private static Demo demo;

 @Autowired
 public void setDemo(Demo d) {
     demo = d;
 }

  public static void callShowDemo(){
       demo.showDemo(); //calling static method from static method
  }

}



回答3:


The above code will not compile at all. You are trying to refer non-static reference from static method, which is not allowed in Java.

Refer this stackoverflow link for better understanding.

Make the following change:

public static Demo demo;



回答4:


when you call DemoStatic.callShowDemo(),the demo may not been instand



来源:https://stackoverflow.com/questions/19946852/calling-non-static-method-from-static-class-in-java-with-spring-autowiring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!