生活随笔
收集整理的這篇文章主要介紹了
SpringBoot用容器IoC管理Bean
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
認識IoC容器和Servlet容器
認識容器
1.IoC容器
IoC(Invension of Control) 容器,是面向對象編程中的一種設計原則,意思是控制反轉。它將程序中創建對象的控制權交給Spring框架來管理,以此來降低代碼之間的耦合度。
在傳統編程中,要實現一種功能一般需要幾個對象相互引用。在主對象中要保存其他類型對象的引用,以便在主對象中實例化對象,然后通過調用這些引用類的方法來完成任務。
而IoC容器的作用是什么呢?要使用某個對象,只需要從IoC容器中獲取使用的對象,不需要關心對象的創建過程,也就是把創建對象的控制權反轉給了Spring框架。
用IoC管理Bean
實驗結果
運行testIoC方法,在控制臺會輸出如下結果
User(id
=1, name
=lishizheng
)
項目目錄
0.添加依賴
該依賴用于測試,不添加注解@Test用不了
<dependency><groupId>junit
</groupId
><artifactId>junit
</artifactId
><version>4.12</version
><scope>test
</scope
></dependency
>
1.創建一個Bean
也就是創建名為“User”的類
User.java
package com
.example
.demo
.entity
;import lombok
.Data
;import java
.io
.Serializable
;@Data
public class User implements Serializable {private int id
;private String name
;
}
2.編寫User的配置類
UserConfig.java,在這里實例化一個對象
代碼的解釋:
@Configuration:用于標注配置類,讓Spring來加載該類配置作為Bean的載體。在運行時,將為這些Bean生成BeanDefinition和服務請求。
@Bean:產生一個Bean,并交給Spring管理。目的是封裝用戶、數據庫中的數據,一般有Setter、Getter方法。
package com
.example
.demo
.config
;import org
.springframework
.context
.annotation
.Bean
;
import org
.springframework
.context
.annotation
.Configuration
;
import com
.example
.demo
.entity
.User
;@Configuration
public class UserConfig {@Bean("user1")public User
user(){User user
=new User();user
.setId(1);user
.setName("lishizheng");return user
;}
}
3.編寫測試類
實例化一個User對象,然后獲取Bean對象user1,該代碼位于test文件夾之下
剛入門的時候這里踩坑:IDEA中cannot resolve method getBean in applicationContext的解決方法
代碼解釋
@SpringBootTest:Spring Boot用于測試的注解,可指定入口類或測試環境等。
@RunWith():讓測試運行于Spring測試環境
@Test:一個測試方法
ApplicationContext:獲取Spring容器中已初始化的Bean,這里是user1
package com
.example
.demo
.config
;
import com
.example
.demo
.entity
.User
;
import org
.junit
.Test
;
import org
.junit
.runner
.RunWith
;
import org
.springframework
.beans
.factory
.annotation
.Autowired
;
import org
.springframework
.boot
.test
.context
.SpringBootTest
;
import org
.springframework
.context
.ApplicationContext
;
import org
.springframework
.test
.context
.junit4
.SpringRunner
;
import static org
.junit
.Assert
.*
;@RunWith(SpringRunner
.class)
@SpringBootTest
public class IoCTest {@Autowiredprivate ApplicationContext applicationContext
;@Testpublic void testIoC(){User user
=(User
)applicationContext
.getBean("user1");System
.out
.println(user
);}
}
總結
以上是生活随笔為你收集整理的SpringBoot用容器IoC管理Bean的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。