简体   繁体   中英

Spring boot bean initialization order

I'm using spring boot for developing a simple REST API but i'm stuck with spring's order to initialize beans of my application . how can i control the order of beans initialization in my application ?

i'm using spring boot 2.1.7 the problem is that spring tries to initialize ContactRestController before SomeService which ContactRestController depends upon so it ends up with the NullPointerException at the constructor of ContactRestController :

@RestController
public class ContactRestController {
    @Autowired
    private SomeService ;
   // no-args constructor 

    public ContactRestControlle(){
       this.someService.doStuff() ;
    }
}

Add SomeService as parameter to constructor, and remove @Autowired from field. Now it's impossible for it to be null.

Alternatively, move the code in the constructor to a @PostConstruct method.

You should read Running Setup Data on Startup in Spring . The guide starts by listing your code as an example of how not to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM