學透Spring Boot — 011. 一篇文章學會Spring Test

系列文章目錄

這是學透Spring Boot的第11篇文章。更多系列文章請關注 CSDN postnull 用戶的專欄


文章目錄

  • 系列文章目錄
  • Spring Test的依賴
  • Spring Test的核心功能
  • `@SpringBootTest` 加載Spring上下文
    • 依賴注入有問題時
    • Spring配置有問題時
  • `@WebMvcTest` 測試Web層(Controller)
    • MockMvc
    • 更多場景
    • Mock 和 Spy
  • @RestClientTest 測試 RestClient
    • 簡單測試
    • MockRestServiceServer 的工作原理
  • @DataJpaTest 測試JPA
    • 簡單使用
    • 原理


前一篇文章,我們介紹了UT、TDD、Mock、Spring Test等概念,本文我們重點來學習一下Spring Test。

Spring Test的依賴

我們要使用Spring Test 第一步要做的事情就是在pom.xml中引入Spring Boot Test的依賴
在這里插入圖片描述
然后會自動關聯相關的依賴
在這里插入圖片描述
這些被關聯進來的包,也就是Spring Test框架使用到的組件(可能是直接使用,也可能是間接使用到的,比如jsonPath就是間接使用, MockMvc封裝了jsonPath)。

組件的具體使用方法,請點擊下面組件的鏈接。

  • JUnit 5: 底層真正使用到單元測試框架.
    在這里插入圖片描述

  • Spring Test & Spring Boot Test: Spring Test的核心,提供了各種測試工具(類和注解)
    在這里插入圖片描述

  • AssertJ: 流式斷言
    在這里插入圖片描述

  • Hamcrest: 用來匹配對象
    在這里插入圖片描述

  • Mockito: Java Mock框架
    在這里插入圖片描述

  • JSONassert: 可以比較json的內容,而不是字符串匹配
    在這里插入圖片描述

  • JsonPath: JSON內容檢測
    在這里插入圖片描述

Spring Test的核心功能

Spring Test 提供了以下核心功能:

  1. @SpringBootTest:用于加載整個 Spring Boot 應用上下文
  2. @ContextConfiguration:用于加載特定的 Spring 配置。
  3. @MockBean 和 @SpyBean:用于模擬 Spring Bean。
  4. TestRestTemplate:用于測試 REST API。
  5. WebTestClient:用于測試 WebFlux 應用。
  6. @DataJpaTest:用來測試JAP 數據庫持久層的代碼
  7. @WebMvcTest:用來測試MVC層

Spring Test 會自動配置各種組件,類似Spring Boot的自動配置,自動配置模塊是 spring-boot-test-autoconfigure

每一種測試場景都是分別使用自己的注解,注解格式都是 @…?Test,他們的自動配置類都是 @AutoConfigure…? 格式

測試模塊注解自動配置類
測試Controller層@WebMvcTestMockMvcAutoConfiguration
測試JPA@DataJpaTestAutoConfigureTestDatabase
測試Spring容器@SpringBootTest
測試RestClient@RestClientTestMockRestServiceServerAutoConfiguration

@SpringBootTest 加載Spring上下文

一個SpringBoot應用,就是一個Spring ApplicationContext(以前我們學習Spring容器時了解過的BeanFactory等各種層級的Spring容器)。

因為是Spring應用,所以我們需要加載完整的Spring Boot應用上下文,用來集成測試,包括我們的依賴正不正確,配置有沒有問題。

當然你也可以直接啟動 Spring Boot應用,但是那樣太麻煩(因為可能你的微服務依賴了一大堆外部系統,比如數據庫、ES等等)。

這時候我們只需要用注解@SpringBootTest 來加載Spring的上下文,快速驗證。
比如,正常情況,我們的測試用例可以通過。

@SpringBootTest
public class JoeApplicationTest {@Autowiredprivate JoeLabApplication applicationContext;@Test@DisplayName("測試Spring應用是否能夠啟動成功")public void contextLoads() {assertNotNull(applicationContext);}
}

依賴注入有問題時

為了測試是不是真的這么強大,我們可以稍微改動一下代碼。把我們的Service層的注解去掉

//@Service
public class TnUserService {public TypiUser getUserById(Integer id){return TypiUser.builder().id(id).name("Joe").username("joe").email("joe@gmail.com").build();}
}

這樣Controller層自動注入會找不到我們的Service。

@RestController
@RequestMapping("/tn-users")
public class TnUserController {private TnUserService tnUserService;public TnUserController(TnUserService tnUserService) {this.tnUserService = tnUserService;}

以前,你需要把Spring應用啟動才能發現這個問題,但是現在只需要執行測試用例。可以看到,測試用例失敗了,因為依賴注入有問題。
在這里插入圖片描述

Spring配置有問題時

我們再換一個case,我們在test/resources下加一個配置application.properties
我們先只配置端口

server.port=6666

運行測試用例,發現報錯了。看錯誤日志。原來是因為我們的classpath下有數據庫的依賴,但是我們的Spring配置文件中沒有任何數據庫的配置造成的。

  1. 引入了數據庫JPA等依賴,就要在application.properties中配置數據庫連接,否則Spring應用啟動報錯的。
  2. test/resources下放置了application.properties,Spring Test就不會去加載src/resources下的application.properties了

在這里插入圖片描述
我們把數據庫的配置加上

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=abc123123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true

這下,測試用例通過了。
在這里插入圖片描述
我們再測試一下,配置有問題的情況. 我們把服務器端口改成abcde

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=aaaaa
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=trueserver.port=abcde

看日志可以看到,Spring Test去實例化Tomcat的bean時報錯了,端口只能是數字
在這里插入圖片描述



@WebMvcTest 測試Web層(Controller)

直接使用Junit + Mockito,我們是不好測試Controller的。所以Spring Test 為我們提供了一個注解 @WebMvcTest

@WebMvcTest(TnUserController.class)
public class TnUserControllerTest {

加了這個注解的case,會自動的配置Spring MVC,并掃描Web相關的配置。比如加了@Controller, @ControllerAdvice等注解的類

但是它不會掃描@Component@ConfigurationProperties的Bean。
要掃描配置類,需要加上@EnableConfigurationProperties 注解
@SpringBootTest更輕量級!只關注Web層的東西。

MockMvc

我們一般不會單獨使用這個注解,而是結合@MockBeanMockMvc 來測試Controller。
MockMvc 這個類可以幫助我們在不需要啟動完整的HTTP服務器的前提下,測試MVC的控制器。

所以,我們的controller的ut通常是這樣的

@WebMvcTest(TnUserController.class)
public class TnUserControllerTest {@Autowiredprivate MockMvc mockMvc;@MockitoBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶的情況")public void testGetUser() throws Exception {//givenTypiUser mockUser = TypiUser.builder().id(1234).name("Joe").build();//whenwhen(tnUserService.getUserById(eq(1234))).thenReturn(mockUser);//thenmockMvc.perform(get("/tn-users/{id}", 1234)).andExpect(status().isBadRequest()).andExpect(jsonPath("$.id").value(1234)).andExpect(jsonPath("$.name").value("Joe"));}
}

jsonPath 用來解析json響應
在這里插入圖片描述

更多場景

  1. 發送Post請求
mockMvc.perform(post("/api/user").contentType(MediaType.APPLICATION_JSON).content("{\"name\": \"Alice\"}")).andExpect(status().isOk()).andExpect(jsonPath("$.message").value("User created"));
  1. 使用jsonPath解析json響應
mockMvc.perform(get("/api/user/1")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1)).andExpect(jsonPath("$.name").value("Alice"));
  1. 請求待header和cookie
        mockMvc.perform(get("/tn-users/{id}", 1234).header("Authorization", "Bearer token123").cookie(new Cookie("token", "token123"))).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1234)).andExpect(jsonPath("$.name").value("Joe"));
  1. 獲取響應,進一步處理
MvcResult result = mockMvc.perform(get("/tn-users/{id}", 1234)).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1234)).andExpect(jsonPath("$.name").value("Joe")).andReturn();
String resp = result.getResponse().getContentAsString();
System.out.println(resp);

在這里插入圖片描述

Mock 和 Spy

Mock 和 Spy都是用來模擬一個類的行為,他們有什么區別呢?

mock用來完全替換一個類
mock是完全模擬,這個類的方法全都會被模擬,如果是void方法,什么也不做。
如果有返回值,這個方法就返回默認值,比如Integer就返回0
如果我們手動配置要返回的值,它就返回我們配置的值。

@Service
public class TnUserService {public Integer getNumber(){return 1000;}
}
    @MockBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber();assertEquals(result, 0);verify(tnUserService, times(1)).getNumber();}

其實還是調用了一次的!!!!

Spy則剛剛相反,如果我們不做任何配置,調用它的方法就直接執行原來的邏輯,除非我們明確要mock它的行為。

    @SpyBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber();assertEquals(result, 0);}

在這里插入圖片描述
稍微改一下,我們還可以驗證方法的調用次數。

    @Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber(1);assertEquals(result, 1000);verify(tnUserService, times(1)).getNumber(eq(1));}

注意@MockBean和@SpyBean都廢棄了

@Deprecated(since = "3.4.0", forRemoval = true)
@Target({ ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(MockBeans.class)
public @interface MockBean {

官方推薦

Deprecated
since 3.4.0 for removal in 3.6.0 in favor of org.springframework.test.context.bean.override.mockito.MockitoBean

可以直接替換

    @MockitoBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber(1);assertEquals(result, 0);}

@SpyBean也一樣

Deprecated
since 3.4.0 for removal in 3.6.0 in favor of org.springframework.test.context.bean.override.mockito.MockitoSpyBean

換了后,不知道為什么報錯。
Unable to select a bean to wrap: there are no beans of type com.joe.joelab.service.TnUserService (as required by field

解決:
這是因為 @WebMvcTest 只會加載Controller 相關的 Bean,不會自動加載 @Service、@Repository 等其他組件。

顯示的引入Service類

@WebMvcTest(TnUserController.class)
@Import(TnUserService.class)
public class TnUserControllerTest {@Autowiredprivate MockMvc mockMvc;@MockitoSpyBeanprivate TnUserService tnUserService;@Test@DisplayName("測試成功查詢用戶數量的情況")public void testGetNumber() throws Exception {Integer result = tnUserService.getNumber(1);assertEquals(result, 1000);}

為什么@SpyBean又能注入呢?

原理:使用@SpyBean 標注一個對象,其實Spring會代理這個對象。

@RestClientTest 測試 RestClient

RestClient是Spring6引入的輕量級同步HTTP客戶端
前面章節已經介紹過如何使用了

@Service
public class TypiRestClientService {private final RestClient.Builder builder;private RestClient restClient;public TypiRestClientService(RestClient.Builder builder) {this.builder = builder;}// 使用 @PostConstruct 注解在 Spring 完成構造器注入后再進行初始化@PostConstructpublic void init() {// 使用 builder 創建 RestClient 實例,進行初始化this.restClient = this.builder.baseUrl("https://jsonplaceholder.typicode.com").build();}public TypiUser getUser(Integer id) {return restClient.get().uri("/users/" + id).retrieve().body(TypiUser.class);}

簡單測試

這里我們來測試一下它

@RestClientTest
@Import(TypiRestClientService.class)
public class TypiRestClientServiceTest {@Autowiredprivate TypiRestClientService typiRestClientService;@Autowiredprivate MockRestServiceServer mockServer;@Testpublic void test(){this.mockServer.expect(requestTo("https://jsonplaceholder.typicode.com/users/1")).andRespond(withSuccess("{\"id\":1, \"name\":\"joe\"}", MediaType.APPLICATION_JSON));TypiUser user = this.typiRestClientService.getUser(1);assertEquals(1, user.getId());assertEquals("joe", user.getName());}}
  • 測試 WebClient 調用外部 REST API 的邏輯,而不會真正發出 HTTP 請求,而是通過 MockRestServiceServer 模擬服務器響應。
    • mockServer會攔截請求并返回響應
  • @RestClientTest 不會加載Service類,所以要Import

MockRestServiceServer 的工作原理

  • Spring Boot 在 @RestClientTest 里會自動配置 RestTemplate 或 RestClient:
    • RestTemplate 需要一個 ClientHttpRequestFactory 作為底層的 HTTP 客戶端。
    • MockRestServiceServer 創建了一個假的 ClientHttpRequestFactory,替換掉默認的 HTTP 處理邏輯。
  • 當 RestTemplate 發出 HTTP 請求時:
    • 由于 RestTemplate 依賴 ClientHttpRequestFactory,而這個工廠已經被 MockRestServiceServer 替換,所有的 HTTP 請求都不會真的出去,而是被攔截。
  • MockRestServiceServer 會檢查是否有匹配的 expect() 規則:
    • 如果 expect(requestTo(…)) 里定義了匹配的 URL,它就會返回你預設的響應(如 withSuccess(…))。
    • 如果沒有匹配的規則,測試會報錯,表示請求沒有預期中的行為。

我們打個斷點,可以看到RestClient的factory已經被替換成mockserver了
在這里插入圖片描述

如果我們要看源碼
可以看自動配置類

@AutoConfiguration
@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver",name = {"enabled"}
)
public class MockRestServiceServerAutoConfiguration {public MockRestServiceServerAutoConfiguration() {}@Beanpublic MockServerRestTemplateCustomizer mockServerRestTemplateCustomizer() {return new MockServerRestTemplateCustomizer();}@Beanpublic MockServerRestClientCustomizer mockServerRestClientCustomizer() {return new MockServerRestClientCustomizer();}@Beanpublic MockRestServiceServer mockRestServiceServer(MockServerRestTemplateCustomizer restTemplateCustomizer, MockServerRestClientCustomizer restClientCustomizer) {try {return this.createDeferredMockRestServiceServer(restTemplateCustomizer, restClientCustomizer);} catch (Exception var4) {throw new IllegalStateException(var4);}}

我們加了這個注解

@RestClientTest
@Import(TypiRestClientService.class)
public class TypiRestClientServiceTest {

其實它是一個符合注解

@TypeExcludeFilters({RestClientTypeExcludeFilter.class})
@AutoConfigureCache
@AutoConfigureWebClient
@AutoConfigureMockRestServiceServer
@ImportAutoConfiguration
public @interface RestClientTest {

它會自動打開自動配置的開關

@PropertyMapping("spring.test.webclient.mockrestserviceserver")
public @interface AutoConfigureMockRestServiceServer {boolean enabled() default true;
}

相當于配置了這個屬性:

spring.test.webclient.mockrestserviceserver = true

自動配置類看到這個是true,就開始配置mockFactory了

@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver",name = {"enabled"}
)
public class MockRestServiceServerAutoConfiguration {

@DataJpaTest 測試JPA

我們可以通過加@RestClientTest注解來測試JPA應用。
默認的,它會掃描@Entity類,并配置JPA Repository.

其它@Component的不會被掃描到。
如果內置的數據庫在classpath,比如h2,它也是會默認配置的。

Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.

我們一般要用h2來測試數據庫。

簡單使用

引入依賴

        <dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.1.210</version><scope>test</scope></dependency>

然后test/resources下配置application.properties 配置數據庫

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

寫測試類

@DataJpaTest
public class BookJpaRepositoryTest {@Autowiredprivate TestEntityManager entityManager;@Autowiredprivate BookJpaRepository bookJpaRepository;@Testpublic void test(){Book book = new Book();book.setName("Hello Java");entityManager.persist(book);Book res = bookJpaRepository.findById(1L).get();assertEquals("Hello Java", res.getName());}
}

Spring Data JPA 測試會自動注入一個TestEntityManager 的bean到測試上下文,我們可以直接注入使用,用來操作數據庫,比如初始化一些測試數據。

原理

毫無疑問,還是自動配置做的好事。
起點還是測試類注解

@DataJpaTest
public class BookJpaRepositoryTest {

它是一個復合注解

@TypeExcludeFilters({DataJpaTypeExcludeFilter.class})
@Transactional
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration
public @interface DataJpaTest {String[] properties() default {};

配置默認內置的數據庫
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/75811.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/75811.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/75811.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Mysql 數據庫編程技術01

一、數據庫基礎 1.1 認識數據庫 為什么學習數據庫 瞬時數據&#xff1a;比如內存中的數據&#xff0c;是不能永久保存的。持久化數據&#xff1a;比如持久化至數據庫中或者文檔中&#xff0c;能夠長久保存。 數據庫是“按照數據結構來組織、存儲和管理數據的倉庫”。是一個長…

新一代AI架構實踐:數字大腦AI+智能調度MCP+領域執行APP的黃金金字塔體系

新一代AI架構實踐&#xff1a;數字大腦智能調度領域執行的黃金金字塔體系 一、架構本質的三層穿透性認知 1.1 核心范式轉變&#xff08;CPS理論升級&#xff09; 傳統算法架構&#xff1a;數據驅動 → 特征工程 → 模型訓練 → 業務應用 新一代AI架構&#xff1a;物理規律建…

macOS可視化桌面配置docker加速器

macOS可視化桌面配置docker加速器 在鏡像settings->docker Engine改為國內鏡像修改為國內鏡像重啟docker(可視化界面啟動或者使用命令行)使用命令重啟可視化界面重啟 在鏡像settings->docker Engine改為國內鏡像 修改為國內鏡像 {"registry-mirrors": ["…

Nginx 基礎使用(2025)

一、Nginx目錄結構 [rootlocalhost ~]# tree /usr/local/nginx /usr/local/nginx ├── client_body_temp # POST 大文件暫存目錄 ├── conf # Nginx所有配置文件的目錄 │ ├── fastcgi.conf # fastcgi相…

用spring-webmvc包實現AI(Deepseek)事件流(SSE)推送

前后端&#xff1a; Spring Boot Angular spring-webmvc-5.2.2包 代碼片段如下&#xff1a; 控制層&#xff1a; GetMapping(value "/realtime/page/ai/sse", produces MediaType.TEXT_EVENT_STREAM_VALUE)ApiOperation(value "獲取告警記錄進行AI分析…

基于Python的招聘推薦數據可視化分析系統

【Python】基于Python的招聘推薦數據可視化分析系統&#xff08;完整系統源碼開發筆記詳細部署教程&#xff09;? 目錄 一、項目簡介二、項目界面展示三、項目視頻展示 一、項目簡介 &#x1f680;&#x1f31f; 基于Python的招聘推薦數據可視化分析系統&#xff01;&#x1…

使用注解開發springMVC

引言 在學習過第一個springMVC項目建造過后&#xff0c;讓我們直接進入真實開發中所必需的注解開發&#xff0c; 是何等的簡潔高效&#xff01;&#xff01; 注&#xff1a;由于Maven可能存在資源過濾的問題&#xff0c;在maven依賴中加入 <build><resources>&l…

linux專題3-----禁止SSH的密碼登錄

要在linux系統中禁止密碼登錄&#xff0c;您可以通過修改 SSH 配置來實現。請按照以下步驟操作(此處以 Ubuntu為例)&#xff1a; 1、SSH 登錄到您的服務器&#xff08;或直接在命令行模式下&#xff09;。 2、備份 SSH 配置文件&#xff1a; 在終端中運行以下命令以備份現有的…

基于LangChain和通義(Tongyi)實現NL2SQL的智能檢索(無需訓練)

在數據驅動的時代,如何高效地從數據庫中獲取信息成為了一個重要的挑戰。自然語言到SQL(NL2SQL)技術提供了一種便捷的解決方案,使用戶能夠用自然語言查詢數據庫,而無需深入了解SQL語法。本文將探討如何利用LangChain和通義(Tongyi)實現NL2SQL的智能檢索,具體步驟如下: …

深度學習處理文本(10)

保存自定義層 在編寫自定義層時&#xff0c;一定要實現get_config()方法&#xff1a;這樣我們可以利用config字典將該層重新實例化&#xff0c;這對保存和加載模型很有用。該方法返回一個Python字典&#xff0c;其中包含用于創建該層的構造函數的參數值。所有Keras層都可以被序…

機器視覺3D中激光偏鏡的優點

機器視覺的3D應用中,激光偏鏡(如偏振片、波片、偏振分束器等)通過其獨特的偏振控制能力,顯著提升了系統的測量精度、抗干擾能力和適應性。以下是其核心優點: 1. 提升3D成像精度 抑制環境光干擾:偏振片可濾除非偏振的環境雜光(如日光、室內照明),僅保留激光偏振信號,大…

線程同步的學習與應用

1.多線程并發 1).多線程并發引例 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <pthread.h>int wg0; void *fun(void *arg) {for(int i0;i<1000;i){wg;printf("wg%d\n",wg);} } i…

寫.NET可以指定運行SUB MAIN嗎?調用任意一個里面的類時,如何先執行某段初始化代碼?

VB.NET 寫.NET可以指定運行SUB MAIN嗎?調用任意一個里面的類時,如何先執行某段初始化代碼? 分享 1. 在 VB.NET 中指定運行 Sub Main 在 VB.NET 里&#xff0c;你能夠指定 Sub Main 作為程序的入口點。下面為你介紹兩種實現方式&#xff1a; 方式一&#xff1a;在項目屬性…

【AI插件開發】Notepad++ AI插件開發實踐(代碼篇):從Dock窗口集成到功能菜單實現

一、引言 上篇文章已經在Notepad的插件開發中集成了選中即問AI的功能&#xff0c;這一篇文章將在此基礎上進一步集成&#xff0c;支持AI對話窗口以及常見的代碼功能菜單&#xff1a; 顯示AI的Dock窗口&#xff0c;可以用自然語言向 AI 提問或要求執行任務選中代碼后使用&…

關聯容器-模板類pair數對

關聯容器 關聯容器和順序容器有著根本的不同:關聯容器中的元素是按關鍵字來保存和訪問的,而順序容器中的元素是按它們在容器中的位置來順序保存和訪問的。 關聯容器支持高效的關鍵字查找和訪問。 兩個主要的關聯容器(associative-container),set和map。 set 中每個元素只包…

京東運維面試題及參考答案

目錄 OSPF 實現原理是什么? 請描述 TCP 三次握手的過程。 LVS 的原理是什么? 闡述 Nginx 七層負載均衡的原理。 Nginx 與 Apache 有什么區別? 如何查看監聽在 8080 端口的是哪個進程(可舉例:netstat -tnlp | grep 8080)? OSI 七層模型是什么,請寫出各層的協議。 …

輸入框輸入數字且保持精度

在項目中如果涉及到金額等需要數字輸入且保持精度的情況下&#xff0c;由于輸入框是可以隨意輸入文本的&#xff0c;所以一般情況下可能需要監聽輸入框的change事件&#xff0c;然后通過正則表達式去替換掉不匹配的文本部分。 由于每次文本改變都會被監聽&#xff0c;包括替換…

使用 requests 和 BeautifulSoup 解析淘寶商品

以下將詳細解釋如何通過這兩個庫來實現按關鍵字搜索并解析淘寶商品信息。 一、準備工作 1. 安裝必要的庫 在開始之前&#xff0c;確保已經安裝了 requests 和 BeautifulSoup 庫。如果尚未安裝&#xff0c;可以通過以下命令進行安裝&#xff1a; bash pip install requests…

C#調用ACCESS數據庫,解決“Microsoft.ACE.OLEDB.12.0”未注冊問題

C#調用ACCESS數據庫&#xff0c;解決“Microsoft.ACE.OLEDB.12.0”未注冊問題 解決方法&#xff1a; 1.將C#采用的平臺從AnyCpu改成X64 2.將官網下載的“Microsoft Access 2010 數據庫引擎可再發行程序包AccessDatabaseEngine_X64”文件解壓 3.安裝解壓后的文件 點擊下載安…

【文獻閱讀】Vision-Language Models for Vision Tasks: A Survey

發表于2024年2月 TPAMI 摘要 大多數視覺識別研究在深度神經網絡&#xff08;DNN&#xff09;訓練中嚴重依賴標注數據&#xff0c;并且通常為每個單一視覺識別任務訓練一個DNN&#xff0c;這導致了一種費力且耗時的視覺識別范式。為應對這兩個挑戰&#xff0c;視覺語言模型&am…