javax.inject @Inject 没有按预期工作

javax.inject @Inject not working as expected

我想了解 javax.inject 是如何工作的,但它似乎没有按预期工作。

package demo333;

import javax.inject.Inject;
import javax.inject.Named;

public class Demo2452 {

    @Inject private @Named("AA1") AA aa;

    public static void main(String[] args) {
        new Demo2452().m2();
    }

    private void m2() {
        System.out.println(aa.hello());
    }

}


interface AA{
    String hello();
}

@Named("AA1")
class AA1 implements AA{

    @Override
    public String hello() {
        return "helllllooooo";
    }

}

我得到 NullPointerException,如下堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException at demo333.Demo2452.m2(Demo2452.java:15) at demo333.Demo2452.main(Demo2452.java:11)

谁能告诉我上面的代码哪里出了问题?

您需要在 class 上添加 @Component

@Component
Class Example{}