了解弹簧靴@Autowired

2022-09-04 07:46:23

我不明白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"); }
}

当我执行此代码时,我获取日志和 ,因此 spring 会创建此对象。但是当我从 in 调用 init 方法时,我得到一个 .除了使用注释来初始化我的对象之外,我还需要做更多的事情吗?init Appinit StarterStarterAppNullPointerException@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

答案 1

当你从类的构造函数调用该方法时,Spring还没有自动将依赖关系连接到对象中。如果要在Spring完成创建并自动连接对象后调用此方法,请添加一个带有注释的方法来执行此操作,例如:initAppAppApp@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();
    }
}

答案 2

推荐