使用Spring自动装配从Java中的静态类调用非静态方法? [英] calling non static method from static class in java with spring autowiring?

查看:122
本文介绍了使用Spring自动装配从Java中的静态类调用非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的接口及其实现类.

I have below interface and its implementation class.

public interface Demo{

 void showDemo();

}

DemoImpl.java

@Service
public class DemoImpl implements Demo{

  public void showDemo(){

       //To Do

    }

}

现在我有一个带有静态方法的类,它将在内部按如下方式调用showDemo().

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

@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.

谢谢!

推荐答案

没有您的设计不正确.

No your design is not correct.

private Demo demo;

必须是

private static Demo demo;

您不能在静态方法中使用NON静态成员

You just cant use NON static members in a static method

这篇关于使用Spring自动装配从Java中的静态类调用非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆