SpringApplication.run: why do we need the "MyApplication.class" parameter when "@SpringBootApplication" annotation presents?

huangapple go评论54阅读模式
英文:

SpringApplication.run: why do we need the "MyApplication.class" parameter when "@SpringBootApplication" annotation presents?

问题

为什么 SpringApplication.run 方法需要一个 MyApplication.class 参数?

Spring 文档中提到:

Parameters: primarySources - the primary sources to load

但当 @SpringBootApplication 存在时,我们已经告诉 Spring Bean 源位于当前包及其子包中,因为 @SpringBootApplication 包括 @ComponentScan。我从 https://www.baeldung.com/spring-component-scanning 上获得了这个理解:

@ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.

因此,当存在 @SpringBootApplication 时,我们不应该需要 MyApplication.class 参数。

为什么需要这个参数?

我是否理解错了什么?

英文:

I always see Spring Boot main class as below:

@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {

      SpringApplication.run(MyApplication.class, args);
  }
}

Why does the SpringApplication.run method need a MyApplication.class argument?

Spring doc says:

> Parameters: primarySources - the primary sources to load

But when @SpringBootApplication presents, we already told Spring that the bean source is in the current package and its sub-packages because @SpringBootApplication includes @ComponentScan. I got his understanding from https://www.baeldung.com/spring-component-scanning:

> @ComponentScan without arguments tells Spring to scan the current
> package and all of its sub-packages.

So, when @SpringBootApplication presents, we should not need the MyApplication.class parameter.

Why is that parameter required?

Did I mis-understand anything?

答案1

得分: 2

如果您不告诉它要在哪里找到标有 @SpringBootApplication 注解的类,它需要扫描所有包以找到它,这会花费很多时间。

因此,明确告诉它 @SpringBootApplication 注解的类的位置可以让它更快地找到它。然后,它可以将其用作起始点,根据其元注解的配置,如 @ComponentScan,来知道要扫描哪些包。

英文:

If you do not tell it where to find the class that is annotated with @SpringBootApplication , it needs to scan all packages to find it out which take lot of times.

So explicit tell it the location of @SpringBootApplication annotated class can make it find it much faster. It can then use it as the starting point to know which packages to scan next based on the configuration of its mete-annotation such as @ComponentScan

huangapple
  • 本文由 发表于 2023年3月4日 08:39:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定