Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple files having @EnableAutoConfiguration annotation

I saw a spring boot project which had @EnableAutoConfiguration defined in the file that main method similar to all Spring Boot projects that I have seen. However I saw this annotation being defined in other java files (file for including Swagger config) within the same project. Should this annotation be defined in multiple files? Will there be any adverse impact in doing this?

like image 609
Punter Vicky Avatar asked Apr 15 '26 15:04

Punter Vicky


2 Answers

@EnableAutoComfiguration should only appear once.

In its simplest form, it won't cause any harm if it's declared multiple times, but there's no benefit. However, if you configure any excludes, those excludes will have to be configured on every occurrence of the annotation as they're not cumulative.

like image 113
Andy Wilkinson Avatar answered Apr 18 '26 05:04

Andy Wilkinson


even it is allowed to have multiples @EnableAutoConfiguration I would recommend to have only one @EnableAutoConfiguration if it is possible. Just because to be able to exclude any configurations which you don't need in the single place. Otherwise the following issue could happen:

  1. here is primary config of spring boot application:

    @SpringBootApplication
    @Import(value = {WebSecurityConfiguration.class})
    public class Application {
        public static void main(String... args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
  2. here is content of WebSecurityConfiguration class

    @Configuration
    public class WebSecurityConfiguration {
            @Configuration
            @EnableAutoConfiguration(exclude ={SecurityAutoConfiguration.class,
            SpringBootWebSecurityConfiguration.class})
            @Profile("dev")
            protected static class DefaultWebSecurityConfig {
            }
    
            @Configuration
            @EnableAutoConfiguration
            @EnableWebSecurity
            protected static class LocalWebSecurityConfig extends WebSecurityConfigurerAdapter {
                //implementation 
            }
    }
    

so, I expected to have security auto configuration disabled for dev profile. But just because @SpringBootApplication defines @EnableAutoConfiguration implicitly appropriate configs were scanned as part of 'primary' @EnableAutoConfiguration and default security settings were applied. as result for dev profile security was enabled.

It would not happened if I defined @EnableAutoConfiguration with excludes just once for Application class.

like image 38
ashirman Avatar answered Apr 18 '26 06:04

ashirman