Reputation: 47913
In the Java Docs for SpringApplication
, it is mentioned that:
SpringApplication
s can read beans from a variety of different sources. It is generally recommended that a single@Configuration
class is used to bootstrap your application [...]
Does this statement mean that it is recommended for an app to only have one @Configuration
class, or is it saying that it is recommended to pass a class that has been annotated with @Configuration
to SpringApplication
(e.g. to its run
method) -- without putting any limitations on the number of @Configuration
classes?
Also I find the rest of the statement difficult to interpret:
[...] however, any of the following sources can also be used:
Class
- A Java class to be loaded byAnnotatedBeanDefinitionReader
Resource
- An XML resource to be loaded byXmlBeanDefinitionReader
, or a groovy script to be loaded byGroovyBeanDefinitionReader
Package
- A Java package to be scanned byClassPathBeanDefinitionScanner
CharSequence
- A class name, resource handle or package name to loaded as appropriate. If theCharSequence
cannot be resolved to class and does not resolve to aResource
that exists it will be considered aPackage
.
While I have used SpringApplication.run
before without any problems, now reading its JavaDocs description has me totally confused.
Upvotes: 0
Views: 295
Reputation: 9526
This is how I understand it :
a single @Configuration class is used to bootstrap your application
You should have one @Configuration class that is the root configuration of your application.
This makes the config much easier to understand and to debug. For sure you can use @Import to import other configurations.
In reality you may have different root configrations for tests and for prod. But you will use always only one as the starting point.
however, any of the following sources can also be used:
That part describes which type of sources can be used to create the application context. These sources can be passed to the constructor :
public SpringApplication(Object... sources)
or a setter :
public void setSources(Set<Object> sources)
I personally have never configured a SpringApplication providing the sources to the constructor or setter. I have one root configuration and annotate my SpringApplication class with @Import.
Upvotes: 1
Reputation: 87
When you using @SpringApplication
or @EnableAutoConfiguration
spring boot will automatically configure your Spring application based on the jar dependencies that you have added
and it should be used just once in your application , On another hand @Configuration
it could be used as many as needed in same root where @SpringApplication
and @EnableAutoConfiguration
.
Spring recommended to have just One primary @Configuration
that add @EnableAutoConfiguration
you can include and exclude as many as you need @Configuration
s to the Primary @EnableAutoConfiguration
from my understanding @EnableAutoConfiguration
and @SpringApplication
almost have same job
Upvotes: 0