[英]Why is a bean declared in @SpringBootApplication class registered even though it is not a stereotyped class?
我的項目中有這個主班
@SpringBootApplication
@EnableOAuth2Sso
public class App
{
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
@Bean public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
}
據我所知,如果我沒有記錯的話,組件掃描會掃描構造型類中的bean,這些類是@Component, @Service, @Repository, @Controller
。
從Spring文檔
默認情況下,僅使用@ Component,@ Repository,@ Service,@ Controller進行注釋的類或使用@Component進行注釋的自定義注釋是唯一檢測到的候選組件。
我不明白該類中的bean是如何注冊的。 由於它不是構造型類,並且沒有使用@Component
注釋的注釋,因此不應首先對其進行掃描,但是此代碼可以完美地工作。 實際上,對於我的用例來說,在此類中包含Bean是解決問題的唯一方法,但這是另一回事。 誰能解釋一下。 謝謝 !!
@SpringBootApplication
是一個元注釋,如下所示:
// Some details omitted
@SpringBootConfiguration
@EnableAutoConfiguration
public @interface SpringBootApplication { ... }
@SpringBootConfiguration
也是一個元注釋:
// Other annotations
@Configuration
public @interface SpringBootConfiguration { ... }
// Other annotations
@Component
public @interface Configuration { ... }
它可以工作,因為:
默認情況下,僅使用@ Component,@ Repository,@ Service,@ Controller進行注釋的類或使用@Component進行注釋的自定義注釋是唯一檢測到的候選組件。
這是因為@SpringBootApplication
還充當@Configuration
批注。
@Configuration
用於創建xml spring configurarion文件中的定義bean。
您可以有一個bean配置類。
@Configuration
class MyConfiguration{
@bean MyBean myBean(){...};
}
o您可以擁有一個Spring配置文件
<beans>
<bean id="myBean" class="MyBean" />
</beans>
在您的情況下,您在使用@SpringBootApplication
取消了Spring配置類
你可以在這里看到更多
http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.