【问题标题】:SpringBoot : Using @Autowired instance inside Runnable Run methodSpringBoot:在 Runnable Run 方法中使用 @Autowired 实例
【发布时间】:2022-08-19 22:59:22
【问题描述】:

我正在尝试在具有 Runnable 的类中使用通过@Autowire 实例化的对象实例,但我得到Null Pointer Exception

我经历了this thread,但我尝试了所有解决方案,但仍然是同样的问题。

分享我的代码:

@Component
public class MyClass{

@Autowired
private ServiceA serviceA;

private String a;
private String b;

public MyClass() {
}
public MyClass(String a, String b) {
this.a = a;
this.b = b;
}
public Runnable newRunnable() {
    return new Runnable() {
        @Override
        public void run() {
           serviceA.innerMethod(a, b);  //got NPE here
        }
     };
  }
}

我称这个类可以像这样从其他类运行

executor.submit(new MyClass(\"abc\", \"def\").newRunnable());

那么,我做错了什么,或者有什么方法可以使用该对象

  • 每当您在任何具有依赖注入的框架中使用 new 时(因此 Spring Boot 以及 Quarkus、CDI 等)什么都不会被注入.该框架不会将自身挂接到构造函数中,它会在您注入这些类的实例时调用这些构造函数。
  • 它是这样工作的,因为您手动创建了这个实例 - new MyClass(\"abc\", \"def\")。如果要注入依赖项,则需要注入abcdef 作为属性,并让Spring 创建MyClass 实例。

标签: java spring spring-boot


【解决方案1】:

你看到的是 NPE,因为 ServiceA 没有注入到你的 MyClass 中。那是因为您通过new 创建了MyClass 关键字,即new MyClass("abc", "def")

尝试从容器中获取MyClass,即

@Autowired MyClass myClass;

并在执行程序中使用 myClass。

executor.submit(myClass.newRunnable());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    相关资源
    最近更新 更多