简体   繁体   中英

How does the EnableAutoConfiguration spring annotation work?

I am no fan of gross over abstractions, And i think Spring has committed a major felony.

But I'm willing to overlook it this time if someone can explain the algorithm behind the 'auto' configuration.

Having a look at spring's own javadocs , It doesn't give much away other than saying that it will intelligently guess what you need and something to do about conditional beans.

Does someone know what algorithm is used to determine what needs to be loaded?

In my experience as a Spring Boot user the basic factors for Spring Boot to decide on what auto-configurations will be enabled are:

1) The classes present on the classpath. For example if RabbitMQ and Spring AMQP classes are present, then the RabbitAutoConfiguration will be enabled. The corresponding annotation is @ConditionalOnClass ,

2) The presence or not of user defined beans. For example, if all the Spring Data JPA is present on the classpath, Spring Boot will register a LocalContainerEntityManagerFactoryBean bean only if the user has not already done so. The beans registered by the user will 'override' the default ones. The relevant annotation is @ConditionalOnMissingBean

As @DaveSyer mentions, you can of course use Spring Boot without @EnableAutoConfiguration if you want to include the relevant configuration on your own. Or you could use the less drastic solution of the exclude field of @EnableAutoConfiguration . If for example you want Spring Boot to autoconfigure everything except ActiveMQ, you would use @EnableAutoConfiguration(exclude=ActiveMQAutoConfiguration.class)

In my opinion, there is absolutely no felony here! You can use what you want from Spring Boot. When you don't want something it has to offer, you can easily opt out partially or completely!

Also if you want to get a look under the covers, you can add the property

logging.level.org.springframework.boot=DEBUG

to application.properties and Spring Boot will gladly give a detailed report of what was auto-configured and what wasn't

There is some documentation in the Spring Boot Reference Guide . It's not terribly complicated, and I hardly think it's a felony to just include a bunch of @Configuration that you might have written anyway (because that's all it does). Feel free not to use @EnableAutoConfiguration if you prefer to include the individual configurations individually.

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