简体   繁体   中英

Spring security and @Configuration order

I was dealing with several spring issues (spring security was usually involved but also other technologies mentioned in tags for this question) with @Configuration ordering where something was initialized "too early" or "too late".

To name an example: When customizing Tomcat: A ServletContext is required to configure default servlet handling

The answer usually was to create separate @Configuration file for some of the beans and then it started to work. The nature of the errors (stacktraces) I was getting didn't usually ring bells which was probably my fault :)

Can someone please point me out where I can find information about why creating separate @Configuration class helps and how the order of @Configuration classes is determined?

Any tips on what to watch for in the stacktrace to identify this type of issues will be also much appreciated.

The reason it sometimes helps is because it gives Spring alternative options for the order of bean creation. An (over-)simplified way of looking at it is to say that if you put everything in one file, then the order is determined by the contents of the file. Whereas, if you break it up, then Spring can explore other options and things can fall into place in another more suitable order. Note that you can use inner classes and package protected classes for @Configuration (as long as they are static), so you don't need to create new files.

A @Configuration class can also be self-contradictory (eg you want to @Autowired something that is created in the same unit - sometimes it works and sometimes not). Also, more often than not in these situations, there are components created by Spring (not by your own code explicitly) that need to be instantiated early. Spring Boot exacerbates that, necessarily, by needing to create Servlets and Filters before the ServletContext is fully initialized.

As far as stack traces go, an @Autowired dependency that turns out to be null is a smell. Also in logs you might see INFO level logs saying the certain beans are 'ineligible for post processing'. That's not guaranteed to be fatal (hence the INFO level) but if you see a lot of it you may be heading for trouble.

I don't know of any canonical reference for this kind of reasoning.

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