What is difference between @ImportAutoConfiguration and @Import

前端 未结 1 575
南旧
南旧 2021-02-19 23:32

Is it true that org.springframework.boot.autoconfigure.ImportAutoConfiguration is improved replacement for org.springframework.context.annotation.Import

相关标签:
1条回答
  • 2021-02-20 00:25

    Is it true that org.springframework.boot.autoconfigure.ImportAutoConfiguration is improved replacement for org.springframework.context.annotation.Import?

    No it is not a replacement since @ImportAutoConfiguration is a Spring Boot specific annotation, I might call it an enhancement. But eventhough it seems that you can use them interchangeably when using Spring Boot, I wouldn't suggest it. Use them as they were intended to be used.


    You would use @ImportAutoConfiguration when you don't want to enable the default autoconfiguration with @EnableAutoConfiguration. As you probably know, @EnableAutoConfiguration attemps to configure beans that are located on your classpath eg tomcat-embedded.jar. Whereas @ImportAutoConfiguration only runs the configuration classes that you provided in the annotation.

    This is an example of an Spring Boot application main method with @ImportAutoConfiguration:

    @ComponentScan("path.to.your.controllers")
    @ImportAutoConfiguration({WebMvcAutoConfiguration.class
        , DispatcherServletAutoConfiguration.class
        , EmbeddedServletContainerAutoConfiguration.class
        , ServerPropertiesAutoConfiguration.class
        , HttpMessageConvertersAutoConfiguration.class})
    public class App {
      public static void main(String[] args) {
        SpringApplication.run(App.class, args);
      }
    }
    

    You might say that it is an alternative to using @EnableAutoConfiguration. And in this case to configure barebone embedded Tomcat and Spring WebMVC.


    @Import is used to import a bean configuration class marked with @Configuration which contains your custom bean configurations.

    0 讨论(0)
提交回复
热议问题