小编典典

了解Spring Boot @Autowired

spring-boot

我不了解Spring Boot的注释如何@Autowired正常工作。这是一个简单的示例:

@SpringBootApplication
public class App {
    @Autowired
    public Starter starter;

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
    public App() {
        System.out.println("init App");
        //starter.init();
    }
}

-

@Repository
public class Starter {
    public Starter() {System.out.println("init Starter");}
    public void init() { System.out.println("call init"); }
}

执行此代码时,我得到了日志init Appinit Starter,因此spring会创建此对象。但是当我从Starterin
调用init方法时App,我得到了一个NullPointerException。除了使用注释@Autowired初始化对象之外,我还需要做更多的事情吗?

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [{package}.App$$EnhancerBySpringCGLIB$$87a7ccf]: Constructor threw exception; nested exception is java.lang.NullPointerException

阅读 606

收藏
2020-05-30

共1个答案

小编典典

当您init从class的构造函数调用该方法时App,Spring尚未将依赖项自动关联到App对象中。如果要在Spring完成App对象的创建和自动装配之后调用此方法,请添加带有@PostConstruct注释的方法来执行此操作,例如:

@SpringBootApplication
public class App {
    @Autowired
    public Starter starter;

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    public App() {
        System.out.println("constructor of App");
    }

    @PostConstruct
    public void init() {
        System.out.println("Calling starter.init");
        starter.init();
    }
}
2020-05-30