@Autowired注解和静态方法

某些业务场景需要我们将方法定义成静态方法,该静态方法还依赖别的被容器管理的类

@Service
public class Foo {

    public int doStuff() {

        System.out.println("hehe");
        return 1;
    }
}

@Component
public class Boo {

    @Autowired
    private static Foo foo;

    public static void test() {
        foo.doStuff();
    }
}

这样必然报java.lang.NullPointerException: null异常,解决办法:

1.将@Autowire加到构造方法上

@Component
public class Boo {
    private static Foo foo;

    @Autowired
    public Boo(Foo foo) {
        Boo.foo = foo;
    }
}

2.用@PostConstruct注解

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    private Foo foo2;

    @PostConstruct
    public void beforeInit() {
        foo = foo2;
    }

    public static void test() {
        foo.doStuff();
    }
}

推荐阅读更多精彩内容