Spring整合單元測驗
目的
減少再我們測驗的時候不停的實體化或者不同的構建Spring容器 就能省略以下代碼
//加載XML檔案,構建Spring容器的代碼
new AnnotationConfigApplicationContext("對應配置類的位元組碼物件");
new ClassPathXmlApplicationContext("applicationContext.xml");
開發步驟
1.首先需要再pom.xml檔案中添加坐標依賴
<!--引入spring-test坐標依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
<scope>test</scope>
</dependency>
<!--引入Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
2.在測驗類上面添加注解, @RunWith(SpringJUnit4ClassRunner.class) 目的就是幫助我我們創建Spring容器
3.在測驗類上賣弄添加注解 @ContextConfiguration(“classpath:applicationContext.xml”) 把主組態檔的類路徑放進來,
到這一步空間一級建立完畢
在測驗包內部
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
4.從容器中取出我們u需要的bean元素,
- getBean()
- 采用注解的屬性注入,@AutoWired @Resource 給類進行屬性注入
首先如果這里需要使用,那么前面就必須要有對應屬性被放入記憶體空間,否則無法獲得
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
// 屬性注入
@Resource(name = "c1") //因為記憶體里面創建了多個物件所以要采用這種方式指定
private Car car;
@Autowired //因為記憶體里面只有一個他的物件所以考研直接使用
private UserController userController;
// 注入UserService類物件
@Autowired //因為記憶體里面只有一個他的物件所以考研直接使用
private UserService userService;
// 注入Proxy01類物件
@Autowired //因為記憶體里面只有一個他的物件所以考研直接使用
private Proxy01 proxy01;
// 注入Proxy02類物件
@Autowired //因為記憶體里面只有一個他的物件所以考研直接使用
private Proxy02 proxy02;
5 測驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/266656.html
標籤:java
上一篇:Python內置庫:concurrent.confutures(簡單異步執行)
下一篇:springcloud
