Spring boot 配置的註解之@Component ,@Configuration與@Bean,以及它們和傳統xml的注入bean的區別

Spring boot 配置的註解之@Component ,@Configuration與@Bean,以及它們和傳統xml的注入bean的區別

目錄

1.傳統xml文件的注入bean

2.Spring boot 配置的註解之@Component

3.Spring boot 配置的註解之@Configuration與@Bean

4.Spring boot 配置的註解與xml的注入bean的區別

5.Spring boot 配置的註解之@Component和@Configuration,@Bean的區別


 

 

1.傳統xml文件的注入bean

在xml文件中,創建一個bean組件,配置和bean組件各個屬性,這樣也就就創建好了一個類實體對象;

<!-- 多文上傳,限制1G文件 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="1073741824" />
	</bean>
	

2.Spring boot 配置的註解之@Component

@Component 註解一個類會作爲組件類,並告知Spring要爲這個類創建bean,也就是自動裝配到Spring容器中。

@Component
@ConfigurationProperties(prefix = "otwx")
public class OtWXConfig {

3.Spring boot 配置的註解之@Configuration與@Bean

@Configuration,相當於xml文件中beans組件,

@Bean要與@Configuration配合使用,@Bean告訴Spring這個方法會返回一個對象實例,這個對象實例也會註冊Spring應用上下文中bean。並且實例名稱默認是方法名,或者可以自己配置一個名稱。自定義性比較好

@Configuration
public class WxMpConfiguration {
    @Bean
    public ExtWxGzhhService extWxGzhhService(){

4.Spring boot 配置的註解與xml的注入bean的區別

Spring boot 配置的註解省去編寫xml文件步驟,也相當省去學習xml語法的功夫

xml文件的注入bean的的方式,更加直觀查看有哪些配置

5.Spring boot 配置的註解之@Component和@Configuration,@Bean的區別

@Component自定義比較差,注入的是Spring容器中,一般自定義對象類中。

@Configuration,@Bean自定義比較好,注入的是Spirng剩下文中。

 

發佈了133 篇原創文章 · 獲贊 45 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章