Why Spring Boot Application class needs to have @Configuration annotation?

后端 未结 2 574
醉梦人生
醉梦人生 2020-12-07 20:27

I am learning about the Spring Framework but I can\'t understand what exactly the @Configuration annotation means and which classes should be annotated so. In t

2条回答
  •  囚心锁ツ
    2020-12-07 21:00

    You understood it right.

    @Configuration

    @Configuration is an analog for xml file. Such classes are sources of bean definitions by defining methods with the @Bean annotation.

    @Configuration is:

    • not required, if you already pass the annotated class in the sources parameter when calling the SpringApplication.run() method;
    • required, when you don't pass the annotated class explicitly, but it's in the package that's specified in the @ComponentScan annotation of your main configuration class.

    For readability, classes that are even explicitly passed as sources may anyway be annotated with @Configuration - just to show the intentions more clearly.

    Your current class is not really source of bean definitions, because it doesn't have any, but if you had @Bean annotated methods, Spring would see them.

    @EnableAutoConfiguration

    Can be used with or without @Configuration. It tells Spring to setup some basic infrastructure judging by what you have in the classpath. It's done by invoking a so called import class that's derived from the value of the @Import annotation that @EnableAutoConfiguration includes. Only one class should be annotated with @EnableAutoConfiguration, duplicating it doesn't do anything.

    This answer may also be helpful to understand the Spring Boot initialization process: Which piece of code in Spring Boot actually registers dispatcher servlet for SpringMVC?

提交回复
热议问题