Understanding Spring Boot @Autowired

前端 未结 1 453
轻奢々
轻奢々 2020-12-31 07:41

I don\'t understand how spring boot\'s annotation @Autowired correctly works. Here is a simple example:

@SpringBootApplication
public class App          


        
相关标签:
1条回答
  • 2020-12-31 08:25

    When you call the init method from the constructor of class App, Spring has not yet autowired the dependencies into the App object. If you want to call this method after Spring has finished creating and autowiring the App object, then add a method with a @PostConstruct annotation to do this, for example:

    @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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题