3.5.5 上下文管理
每個TestContext
為其負責的測試實例提供上下文管理和緩存支持。測試實例不會自動接收對配置的ApplicationContext
的訪問。但是,如果測試類實現ApplicationContextAware
接口,則將對ApplicationContext
的引用提供給測試實例。請注意,AbstractJUnit4SpringContextTests
和AbstractTestNGSpringContextTests
實現了ApplicationContextAware
,因此可以自動提供對ApplicationContext
的訪問。
@Autowired
ApplicationContext
作為實現
ApplicationContextAware
接口的替代方法,你可以通過字段或setter
方法上的@Autowired
註解為測試類注入應用程序上下文,如以下示例所示:@SpringJUnitConfig class MyTest { @Autowired //1 ApplicationContext applicationContext; // class body... }
- 注入
ApplicationContext
。同樣,如果將測試配置為加載
WebApplicationContext
,則可以將Web應用程序上下文注入到測試中,如下所示:@SpringJUnitWebConfig //1 class MyWebAppTest { @Autowired //2 WebApplicationContext wac; // class body... }
- 配置
WebApplicationContext
- 注入
WebApplicationContext
使用
@Autowired
的依賴關係注入是DependencyInjectionTestExecutionListener
提供的,它是默認配置的(參見測試裝置的依賴注入)。
使用TestContext
框架的測試類不需要擴展任何特定的類或實現特定的接口來配置其應用程序上下文。而是通過在類級別聲明@ContextConfiguration
註解來實現配置。如果你的測試類未明確聲明應用程序上下文資源位置或組件類,則配置的ContextLoader
將確定如何從默認位置或默認配置類加載上下文。除了上下文資源位置和組件類之外,還可以通過應用程序上下文初始化程序配置應用程序上下文。
以下各節說明如何使用Spring的@ContextConfiguration
註解通過XML配置文件、Groovy
腳本、組件類(通常為@Configuration
類)或上下文初始化器來配置測試ApplicationContext
。另外,你可以為高級用例實現和配置自己的自定義SmartContextLoader
。
- 通過XML資源配置上下文
- 通過Groovy腳本配置上下文
- 通過組件類配置上下文
- XML、Groovy腳本、組件類混合
- 通過上下文初始化器配置上下文
- 上下文配置繼承
- 通過環境配置配置上下文
- 通過測試屬性源配置上下文
- 通過動態屬性源配置上下文
- 加載
WebApplicationContext
- 上下文緩存
- 上下文層級
通過XML資源配置上下文
若要使用XML配置文件為測試加載ApplicationContext
,請使用@ContextConfiguration
註解測試類,並使用包含XML配置元數據的資源位置的數組配置locations
屬性。簡單路徑或相對路徑(例如context.xml
)被視為相對於定義測試類的程序包的類路徑資源。以斜槓開頭的路徑被視為絕對類路徑位置(例如:/org/example/config.xml
)。照原樣使用表示資源URL的路徑(即以classpath:
、file:
、http:
等開頭的路徑)。
@ExtendWith(SpringExtension.class)
// ApplicationContext從根路徑加載"/app-config.xml" 和
// "/test-config.xml"
@ContextConfiguration(locations={"/app-config.xml", "/test-config.xml"}) //1
class MyTest {
// class body...
}
- 將
locations
屬性設置為XML文件列表。
@ContextConfiguration
通過標準Java值屬性為locations
屬性支持別名。因此,如果不需要在@ContextConfiguration
中聲明其他屬性,你可以使用以下示例中演示的格式,省略locations
屬性名稱的聲明並聲明資源位置。
@ExtendWith(SpringExtension.class)
@ContextConfiguration({"/app-config.xml", "/test-config.xml"}) //1
class MyTest {
// class body...
}
- 不使用
location
屬性指定XML文件。
如果你從@ContextConfiguration
註解中省略了位置和值屬性,則TestContext
框架將嘗試檢測默認的XML資源位置。具體而言,GenericXmlContextLoader
和GenericXmlWebContextLoader
根據測試類的名稱檢測默認位置。如果你的類名為com.example.MyTest
則GenericXmlContextLoader
將classpath:com/example/MyTest-context.xml
加載應用程序上下文。以下示例顯示瞭如何執行此操作:
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration //1
class MyTest {
// class body...
}
- 從默認位置加載配置。
通過Groovy腳本配置上下文
要通過使用Groovy Bean定義DSL的Groovy腳本為測試加載ApplicationContext
,可以使用@ContextConfiguration
註解測試類,並使用包含Groovy腳本資源位置的數組配置location
或value
屬性。Groovy腳本的資源查找語義與針對XML配置文件描述的語義相同。
激活Groovy腳本支持
如果類路徑中有Groovy,那麼就會自動啟用使用Groovy腳本在Spring
TestContext
框架中加載ApplicationContext
的支持。
下面的示例顯示如何指定Groovy配置文件:
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "/AppConfig.groovy" and
// "/TestConfig.groovy" in the root of the classpath
@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"})
class MyTest {
// class body...
}
如果你從@ContextConfiguration
註解中省略了location
和value
屬性,則TestContext
框架將嘗試檢測默認的Groovy腳本。具體來說,GenericGroovyXmlContextLoader
和GenericGroovyXmlWebContextLoader
根據測試類的名稱檢測默認位置。如果你的類名為com.example.MyTest
則Groovy上下文加載器將從classpath:com/example/MyTestContext.groovy
加載應用程序上下文。下面的示例演示如何使用默認值:
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration //1
class MyTest {
// class body...
}
- 從默認位置加載配置。
同時聲明XML配置和Groovy腳本
你可以使用
@ContextConfiguration
的location
或value
屬性同時聲明XML配置文件和Groovy腳本。如果到配置的資源位置的路徑以.xml
結尾,則使用XmlBeanDefinitionReader
加載該路徑。否則,將使用GroovyBeanDefinitionReader
加載它。以下清單顯示瞭如何在集成測試中將兩者結合起來:
@ExtendWith(SpringExtension.class) // ApplicationContext將從 // "/app-config.xml" 和 "/TestConfig.groovy"加載上下文 @ContextConfiguration({ "/app-config.xml", "/TestConfig.groovy" }) class MyTest { // class body... }
通過組件類配置上下文
要使用組件類(請參見基於Java的容器配置)為測試加載ApplicationContext
,可以使用@ContextConfiguration
註解測試類,並使用包含對組件類的引用的數組來配置classes
屬性。以下示例顯示瞭如何執行此操作:
@ExtendWith(SpringExtension.class)
// ApplicationContext將從AppConfig和TestConfig加載上下文
@ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) //1
class MyTest {
// class body...
}
- 指定組件類。
組件類
術語
組件類
可以指以下任何一種:
- 用
@Configuration
註解的類。- 組件(即,用
@Component
、@Service
、@Repository
或其他構造型註解註釋的類)。- 與JSR-330兼容的類,該類使用
javax.inject
註解進行了註釋。- 包含
@Bean
方法的任何類。- 打算註冊為Spring組件的任何其他類(即
ApplicationContext
中的Spring bean),可能利用單個自動構造函數的自動裝配而無需使用Spring註解。有關組件類的配置和語義的更多信息,請參見@Configuration和@Bean的javadoc,尤其要注意
@Bean
Lite模式的討論。
如果你從@ContextConfiguration
註解中省略了classes
屬性,則TestContext
框架將嘗試檢測默認配置類的存在。具體來說,AnnotationConfigContextLoader
和AnnotationConfigWebContextLoader
檢測到滿足配置類實現要求的測試類的所有靜態嵌套類,如@Configuration javadoc中所指定。請注意,配置類的名稱是任意的。另外,如果需要,一個測試類可以包含多個靜態嵌套配製類。在以下示例中,OrderServiceTest
類聲明一個名為Config
的靜態嵌套配置類,該配置類將自動用於為測試類加載ApplicationContext
:
@SpringJUnitConfig //1
// ApplicationContext將從內部潛逃靜態累加載
class OrderServiceTest {
@Configuration
static class Config {
// this bean will be injected into the OrderServiceTest class
@Bean
OrderService orderService() {
OrderService orderService = new OrderServiceImpl();
// set properties, etc.
return orderService;
}
}
@Autowired
OrderService orderService;
@Test
void testOrderService() {
// test the orderService
}
}
- 從嵌套的Config類加載配置信息。
XML、Groovy腳本、組件類混合
有時可能需要混合使用XML配置文件、Groovy腳本和組件類(通常為@Configuration
類)來為測試配置ApplicationContext
。如果在生產中使用XML配置,則可以決定要使用@Configuration
類為測試配置特定的Spring託管組件,反之亦然。
此外,某些第三方框架(例如Spring Boot)提供了一流的支持,可以同時從不同類型的資源(例如XML配置文件、Groovy腳本和@Configuration
類)中加載ApplicationContext
。過去,Spring框架不支持此標準部署。因此,Spring框架在spring-test
模塊中提供的大多數SmartContextLoader
實現對於每個測試上下文僅支持一種資源類型。但是,這並不意味著你不能同時使用兩者。通用規則的一個例外是GenericGroovyXmlContextLoader
和GenericGroovyXmlWebContextLoader
同時支持XML配置文件和Groovy腳本。此外,第三方框架可以選擇通過@ContextConfiguration
支持位置和類的聲明,並且,藉助TestContext
框架中的標準測試支持,你可以選擇以下選項。
如果要使用資源位置(例如XML或Groovy)和@Configuration
類的配置測試,則必須選擇一個作為入口點,並且其中一個必須包含或導入另一個。例如,在XML或Groovy腳本中,可以通過使用組件掃描或將它們定義為普通的Spring bean來包括@Configuration
類,而在@Configuration
類中,可以使用@ImportResource
導入XML配置文件或Groovy腳本。請注意,此行為在語義上等同於你在生產環境中配置應用程序的方式:在生產配置中,你定義了一組XML或Groovy資源位置或一組@Configuration
類,從中加載了生產ApplicationContext
,但是你仍然包含或導入其他類型的配置的自由。
通過上下文初始化器配置上下文
若要使用上下文初始化程序為你的測試配置ApplicationContext
,請使用@ContextConfiguration
註解測試類,並使用包含對實現ApplicationContextInitializer
的類的引用的數組配置初始化程序屬性。然後,使用聲明的上下文初始值設定項來初始化為測試加載的ConfigurableApplicationContext
。請注意,每個聲明的初始化程序支持的具體ConfigurableApplicationContext
類型必須與使用中的SmartContextLoader
創建的ApplicationContext
類型(通常是GenericApplicationContext
)兼容。此外,初始化程序的調用順序取決於它們是實現Spring的Ordered
接口還是以Spring的@Order
註解或標準的@Priority
註解進行註釋。下面的示例演示如何使用初始化程序:
@ExtendWith(SpringExtension.class)
// ApplicationContext將從TestConfig
// 和 通過TestAppCtxInitializer初始化
@ContextConfiguration(
classes = TestConfig.class,
initializers = TestAppCtxInitializer.class) //1
class MyTest {
// class body...
}
- 使用配置類和初始化程序指定配置。
你還可以完全省略@ContextConfiguration
中的XML配置文件、Groovy腳本或組件類的聲明,而僅聲明ApplicationContextInitializer
類,然後這些類負責在上下文中註冊Bean(例如,通過編程方式從XML文件加載Bean定義)或配置類。以下示例顯示瞭如何執行此操作:
@ExtendWith(SpringExtension.class)
// ApplicationContext will be initialized by EntireAppInitializer
// which presumably registers beans in the context
@ContextConfiguration(initializers = EntireAppInitializer.class) //1
class MyTest {
// class body...
}
- 僅使用初始化程序來指定配置。
參考代碼:
org.liyong.test.annotation.test.spring.ContextInitializerTests
上下文配置繼承
@ContextConfiguration
支持boolean
inheritLocations
和inheritinitialalizer
屬性,它們表示是否應該繼承由超類聲明的資源位置或組件類和上下文初始化器。這兩個標誌的默認值為true
。這意味著測試類將繼承資源位置或組件類以及任何超類申明的上下文初始化器。具體來說,將測試類的資源位置或組件類附加到由超類申明的資源位置或帶註解的類的列表中。同樣,將給定測試類的初始化程序添加到由測試超類定義的初始化程序集。因此,子類可以選擇擴展資源位置、組件類或上下文初始化程序。
如果@ContextConfiguration
中的inheritLocations
或inheritInitializers
屬性被設置為false
,則測試類的資源位置或組件類和上下文初始化器將分別有效地替代超類定義的配置。
在下一個使用XML資源位置的示例中,從Base-config.xml
和Extended-config.xml依
次加載ExtendedContext
的ApplicationContext
。因此,extended-config.xml
中定義的Bean可以覆蓋(即替換)base-config.xml
中定義的那些。以下示例顯示了一個類如何擴展另一個類並使用其自己的配置文件和超類的配置文件:
@ExtendWith(SpringExtension.class)
// ApplicationContext將從類路徑根目錄加載"/base-config.xml"
@ContextConfiguration("/base-config.xml") //1
class BaseTest {
// class body...
}
// ApplicationContext將從類路徑根目錄加載"/base-config.xml" 和
// "/extended-config.xml"
@ContextConfiguration("/extended-config.xml") //2
class ExtendedTest extends BaseTest {
// class body...
}
- 在超類中定義的配置文件
- 子類中定義的配置文件。
同樣,在下一個使用組件類的示例中,從BaseConfig
和ExtendedConfig
類按該順序加載ExtendedTest
的ApplicationContext
。因此,在ExtendedConfig
中定義的Bean可以覆蓋(即替換)在BaseConfig
中定義的Bean。下面的示例顯示一個類如何擴展另一個類,並同時使用自己的配置類和超類的配置類:
// ApplicationContext從BaseConfig加載
@SpringJUnitConfig(BaseConfig.class) //1
class BaseTest {
// class body...
}
// ApplicationContext將從BaseConfig和ExtendedConfig加載
@SpringJUnitConfig(ExtendedConfig.class) //2
class ExtendedTest extends BaseTest {
// class body...
}
- 在超類中定義的配置類
- 在子類中定義的配置類。
在使用上下文初始化程序的下一個示例中,通過使用BaseInitializer
和ExtendedInitializer
初始化ExtendedTest
的ApplicationContext
。但是請注意,初始化程序的調用順序取決於它們是實現Spring的Ordered
接口還是以Spring的@Order
註解或標準的@Priority
註解進行註釋。以下示例顯示了一個類如何擴展另一個類並使用其自己的初始化程序和超類的初始化程序:
// ApplicationContext將通過BaseInitializer初始化
@SpringJUnitConfig(initializers = BaseInitializer.class) //1
class BaseTest {
// class body...
}
// ApplicationContext將通過BaseInitializer
// 和 ExtendedInitializer初始化
@SpringJUnitConfig(initializers = ExtendedInitializer.class) //2
class ExtendedTest extends BaseTest {
// class body...
}
- 超類中定義的初始化器。
- 子類中定義的初始化程序。
使用環境配置文件進行上下文配置
Spring框架對環境和配置文件(又名“bean定義配置文件”)的概念提供了一流的支持,可以配置集成測試來激活針對各種測試場景的特定bean定義配置文件。這可以通過使用@ActiveProfiles
註解測試類並提供在加載測試的ApplicationContext
時應激活的配置文件列表來實現。
你可以將
@ActiveProfiles
與SmartContextLoader
SPI的任何實現一起使用,但較早的ContextLoader
SPI的實現不支持@ActiveProfiles
。
考慮兩個帶有XML配置和@Configuration
類的示例:
<!-- app-config.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="...">
<bean id="transferService"
class="com.bank.service.internal.DefaultTransferService">
<constructor-arg ref="accountRepository"/>
<constructor-arg ref="feePolicy"/>
</bean>
<bean id="accountRepository"
class="com.bank.repository.internal.JdbcAccountRepository">
<constructor-arg ref="dataSource"/>
</bean>
<bean id="feePolicy"
class="com.bank.service.internal.ZeroFeePolicy"/>
<beans profile="dev">
<jdbc:embedded-database id="dataSource">
<jdbc:script
location="classpath:com/bank/config/sql/schema.sql"/>
<jdbc:script
location="classpath:com/bank/config/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans>
<beans profile="production">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>
<beans profile="default">
<jdbc:embedded-database id="dataSource">
<jdbc:script
location="classpath:com/bank/config/sql/schema.sql"/>
</jdbc:embedded-database>
</beans>
</beans>
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "classpath:/app-config.xml"
@ContextConfiguration("/app-config.xml")
@ActiveProfiles("dev")
class TransferServiceTest {
@Autowired
TransferService transferService;
@Test
void testTransferService() {
// test the transferService
}
}
運行TransferServiceTest
時,會從類路徑根目錄中的app-config.xml
配置文件中加載其ApplicationContext
。如果檢查app-config.xml
,可以看到accountRepository bean對dataSource
bean有依賴性。但是,dataSource
未被定義為頂級bean。相反,dataSource
定義了三次:在生產配置文件中、在開發配置文件中以及在默認配置文件中。
通過使用@ActiveProfiles(“dev”)
註解TransferServiceTest
,我們指示Spring TestContext
框架加載具有設置為{“dev”}
的激活配置文件的ApplicationContext
。結果,創建了一個嵌入式數據庫,並用測試數據填充了數據庫,並用對開發DataSource
的引用來連接accountRepository
bean。這可能是我們在集成測試中想要的。
有時將bean分配給默認配置文件很有用。只有在沒有特別激活其他配置文件時,才會包含缺省配置文件中的bean。你可以使用它來定義在應用程序的默認狀態中使用的後備bean。例如,你可以顯式提供dev
和production
的數據源,但是當兩者都不處於活動狀態時,將內存中數據源定義為默認值。
以下代碼清單演示瞭如何使用@Configuration
類而不是XML實現相同的配置和集成測試:
@Configuration
@Profile("dev")
public class StandaloneDataConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.addScript("classpath:com/bank/config/sql/test-data.sql")
.build();
}
}
@Configuration
@Profile("production")
public class JndiDataConfig {
@Bean(destroyMethod="")
public DataSource dataSource() throws Exception {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
}
}
@Configuration
@Profile("default")
public class DefaultDataConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.build();
}
}
@Configuration
public class TransferServiceConfig {
@Autowired DataSource dataSource;
@Bean
public TransferService transferService() {
return new DefaultTransferService(accountRepository(), feePolicy());
}
@Bean
public AccountRepository accountRepository() {
return new JdbcAccountRepository(dataSource);
}
@Bean
public FeePolicy feePolicy() {
return new ZeroFeePolicy();
}
}
@SpringJUnitConfig({
TransferServiceConfig.class,
StandaloneDataConfig.class,
JndiDataConfig.class,
DefaultDataConfig.class})
@ActiveProfiles("dev")
class TransferServiceTest {
@Autowired
TransferService transferService;
@Test
void testTransferService() {
// test the transferService
}
}
在此變體中,我們將XML配置分為四個獨立的@Configuration
類:
-
ransferServiceConfig
: 通過使用@Autowired
進行依賴項注入來獲取數據源。 -
StandaloneDataConfig
: 為適合開發人員測試的嵌入式數據庫定義數據源。 -
JndiDataConfig
: 定義在生產環境中從JNDI檢索的數據源。 -
DefaultDataConfig
: 如果沒有配置文件處於激活狀態,則為默認的嵌入式數據庫定義一個數據源。
與基於XML的配置示例一樣,我們仍然使用@ActiveProfiles("dev")
註解TransferServiceTest
,但是這次我們使用@ContextConfiguration
註解指定所有四個配置類。測試類的主體本身保持完全不變。
在一個給定項目中,跨多個測試類使用一組配置文件是很常見的。因此,為避免@ActiveProfiles
註解的重複聲明,可以在基類中聲明一次@ActiveProfiles
,子類會自動從基類繼承@ActiveProfiles
配置。在以下示例中,@ActiveProfiles
的聲明(以及其他註解)已移至抽象超類AbstractIntegrationTest
:
@SpringJUnitConfig({
TransferServiceConfig.class,
StandaloneDataConfig.class,
JndiDataConfig.class,
DefaultDataConfig.class})
@ActiveProfiles("dev")
abstract class AbstractIntegrationTest {
}
// "dev"配置集成父類
class TransferServiceTest extends AbstractIntegrationTest {
@Autowired
TransferService transferService;
@Test
void testTransferService() {
// test the transferService
}
}
@ActiveProfiles
還支持可用於禁用激活配置文件的繼承的InheritedProfiles
屬性,如以下示例所示:
// "dev"配置被"production"覆蓋
@ActiveProfiles(profiles = "production", inheritProfiles = false)
class ProductionTransferServiceTest extends AbstractIntegrationTest {
// test body
}
此外,有時有必要以編程方式而不是聲明方式來解析測試的激活配置文件,例如,基於:
- 當前的操作系統。
- 是否在持續集成構建服務器上執行測試。
- 存在某些環境變量。
- 自定義類級別註釋的存在。
- 其他問題。
要以編程方式解析活動bean定義配置文件,可以實現自定義ActiveProfilesResolver
並使用@ActiveProfiles
的resolver
屬性對其進行註冊。有關更多信息,請參見相應的javadoc。下面的示例演示如何實現和註冊自定義的OperatingSystemActiveProfilesResolver
:
// "dev"配置通過自定義解析器編程式地覆蓋
@ActiveProfiles(
resolver = OperatingSystemActiveProfilesResolver.class,
inheritProfiles = false)
class TransferServiceTest extends AbstractIntegrationTest {
// test body
}
public class OperatingSystemActiveProfilesResolver implements ActiveProfilesResolver {
@Override
public String[] resolve(Class<?> testClass) {
String profile = ...;
// determine the value of profile based on the operating system
return new String[] {profile};
}
}
通過測試屬性源配置上下文
Spring框架對具有屬性源層次結構的環境概念提供了一流的支持,你可以使用特定於測試的屬性源配置集成測試。與@Configuration
類上使用的@PropertySource
註解相反,可以在測試類上聲明@TestPropertySource
註解,以聲明測試屬性文件或內聯屬性的資源位置。這些測試屬性源被添加到環境中為帶註解的集成測試加載的ApplicationContext
的PropertySources
集合中。
你可以將
@TestPropertySource
與SmartContextLoader
SPI的任何實現一起使用,但是較早的ContextLoader
SPI的實現不支持@TestPropertySource
。
SmartContextLoader
的實現可通過MergedContextConfiguration
中的getPropertySourceLocations()
和getPropertySourceProperties()
方法訪問合併的測試屬性源值。
聲明測試屬性源
你可以使用@TestPropertySource的location
或value
屬性來配置測試屬性文件。
支持傳統屬性文件格式和基於XML的屬性文件格式,例如: classpath:/com/example/test.properties
或file:///path/to/file.xml
。
每個路徑都被解析為Spring資源。普通路徑(例如 test.properties
)被視為相對於定義測試類的程序包的類路徑資源。以斜槓開頭的路徑被視為絕對類路徑資源(例如:/org/example/test.xml
)。通過使用指定的資源協議加載引用URL的路徑(例如,以classpath:
、file:
或http:
為前綴的路徑)。不允許使用資源位置通配符(例如* /.properties
)每個位置都必須精確評估為一個.properties
或.xml
資源。
以下示例使用測試屬性文件:
@ContextConfiguration
@TestPropertySource("/test.properties") //1
class MyIntegrationTests {
// class body...
}
- 指定具有絕對路徑的屬性文件。
你可以使用@TestPropertySource
的properties
屬性,以鍵/值對的形式配置內聯屬性,如下例所示。所有鍵值對都作為優先級最高的單個測試PropertySource
添加到封閉環境中。
鍵值對支持的語法與為Java屬性文件中的條目定義的語法相同:
key=value
key:value
key value
下面的示例設置兩個內聯屬性:
@ContextConfiguration
@TestPropertySource(properties = {"timezone = GMT", "port: 4242"}) //1
class MyIntegrationTests {
// class body...
}
- 通過使用鍵值語法的兩種變體來設置兩個屬性。
從Spring框架5.2開始,
@TestPropertySource
可以用作可重複註解。這意味著你可以在單個測試類上具有@TestPropertySource
的多個聲明,其後的@TestPropertySource
註解中的locations
和properties
將覆蓋先前的@TestPropertySource
註解中的locations
和properties
。此外,你可以在一個測試類上聲明多個組合註解,每個註解都用
@TestPropertySource
進行元註解,所有這些@TestPropertySource
聲明都將貢獻給你的測試屬性源。直接呈現的@TestPropertySource註解
總是優先於元呈現的@TestPropertySource
註解。換句話說,直接存在的@TestPropertySource
註解中的locations
和properties
將覆蓋@TestPropertySource
註解中用作元註解的locations
和properties
。
默認屬性文件檢測
如果@TestPropertySource
被聲明為空註解(即,沒有locations
或properties
的顯式值),則嘗試檢測相對於聲明該註解的類的默認屬性文件。例如,如果帶註解的測試類是com.example.MyTest
,則相應的對應屬性文件是classpath:com/example/MyTest.properties
。如果無法檢測到默認值,則拋出IllegalStateException
。
優先順序
測試屬性的優先級高於在操作系統環境、Java系統屬性或應用程序通過使用@PropertySource
聲明性地或以編程方式添加的屬性源中定義的屬性。因此,測試屬性可用於有選擇地覆蓋從系統和應用程序屬性源加載的屬性。此外,內聯屬性優先於從資源位置加載的屬性。但是請注意,通過@DynamicPropertySource
註冊的屬性比通過@TestPropertySource
加載的屬性具有更高的優先級。
在下一個示例中,timezone
和port
屬性以及在/test.properties
中定義的任何屬性都將覆蓋在系統和應用程序屬性源中定義的同名屬性。此外,如果/test.properties
文件定義了timezone
和port
屬性的條目,則這些條目將被使用properties
屬性聲明的內聯屬性所覆蓋。
@ContextConfiguration
@TestPropertySource(
locations = "/test.properties",
properties = {"timezone = GMT", "port: 4242"}
)
class MyIntegrationTests {
// class body...
}
繼承和覆蓋測試屬性源
@TestPropertySource
支持布爾型的inheritLocations
和inheritProperties
屬性,它們表示屬性文件的資源位置和超類聲明的內聯屬性是否應該被繼承。這兩個標誌的默認值為true
。這意味著測試類將繼承任何超類聲明的位置和內聯屬性。具體來說,測試類的位置和內聯屬性附加到父類聲明的位置和內聯屬性。因此,子類可以選擇擴展位置和內聯屬性。注意,後面出現的屬性會隱藏(即覆蓋)前面出現的同名屬性。此外,前面提到的優先規則也適用於繼承的測試屬性源。
如果@TestPropertySource
中的InheritLocations
或InheritProperties
屬性設置為false
,則分別為測試類設置位置或內聯屬性,並有效替換超類定義的配置。
在下一個示例中,BaseTest
的ApplicationContext
是通過只使用base
加載的。屬性文件作為測試屬性源。相反,ExtendedTest
的ApplicationContext
是通過使用base
加載的屬性和擴展。屬性文件作為測試屬性源位置。下面的示例演示如何使用屬性文件在子類及其超類中定義屬性:
@TestPropertySource("base.properties")
@ContextConfiguration
class BaseTest {
// ...
}
@TestPropertySource("extended.properties")
@ContextConfiguration
class ExtendedTest extends BaseTest {
// ...
}
在下一個示例中,僅使用內聯的key1
屬性來加載BaseTest
的ApplicationContext
。相反,使用內聯的key1
和key2
屬性來加載ExtendedTest
的ApplicationContext
。下面的示例演示如何通過使用內聯屬性在子類及其父類中定義屬性:
@TestPropertySource(properties = "key1 = value1")
@ContextConfiguration
class BaseTest {
// ...
}
@TestPropertySource(properties = "key2 = value2")
@ContextConfiguration
class ExtendedTest extends BaseTest {
// ...
}
通過動態屬性源配置上下文
從Spring框架5.2.5開始,TestContext
框架通過@DynamicPropertySource
註解提供對動態屬性的支持。此註解可用於需要向為集成測試加載的ApplicationContext
的環境中的PropertySources
集添加帶有動態值的屬性的集成測試。
@DynamicPropertySource
註解及其支持的基礎結構最初旨在使基於Testcontainers
的測試中的屬性易於暴露於Spring集成測試。但是,此功能還可以用於其生命週期在測試的ApplicationContext
之外維護的任何形式的外部資源。
與在類級別應用@TestPropertySource
註解相反,@DynamicPropertySource
必須應用於接受單個DynamicPropertyRegistry
參數的靜態方法,該參數用於向環境添加名稱/值
對。值是動態的,並通過Supplier
提供,只有在解析屬性時才調用Supplier
。通常,方法引用被用來提供值,如下面的例子所示,它使用Testcontainers
項目在Spring ApplicationContext
之外管理一個Redis容器。通過redis.host
和redis.port
屬性,測試的ApplicationContext
中的組件可以使用託管Redis容器的IP地址和端口。這些屬性可以通過Spring的環境抽象訪問,或者直接注入到Spring管理的組件中,例如分別通過@Value("${redis.host}")
和@Value("${redis.port}")
。
@SpringJUnitConfig(/* ... */)
@Testcontainers
class ExampleIntegrationTests {
@Container
static RedisContainer redis = new RedisContainer();
@DynamicPropertySource
static void redisProperties(DynamicPropertyRegistry registry) {
registry.add("redis.host", redis::getContainerIpAddress);
registry.add("redis.port", redis::getMappedPort);
}
// tests ...
}
優先順序
動態屬性的優先級高於@TestPropertySource
、操作系統的環境、Java系統屬性或應用程序通過@PropertySource
聲明性地或以編程方式添加的屬性源中加載的屬性。因此,動態屬性可用於有選擇地覆蓋通過@TestPropertySource
、系統屬性源和應用程序屬性源加載的屬性。
加載WebApplicationContext
若要指示TestContext
框架加載WebApplicationContext
而不是標準ApplicationContext
,可以使用@WebAppConfiguration
註解各自的測試類。
測試類上@WebAppConfiguration
的存在指示TestContext
框架(TCF)應該為集成測試加載WebApplicationContext
(WAC)。TCF在後臺確保創建了MockServletContext
並將其提供給測試的WAC。默認情況下,你的MockServletContext
的基本資源路徑設置為src/main/webapp
。這被解釋為相對於JVM根目錄的路徑(通常是項目的路徑)。如果你熟悉Maven項目中Web應用程序的目錄結構,則知道src/main/webapp
是WAR根目錄的默認位置。如果需要覆蓋此默認值,則可以提供@WebAppConfiguration
註解的替換路徑(例如,@WebAppConfiguration(“src/test/webapp”))
。如果你希望從類路徑而不是文件系統中引用基本資源路徑,則可以使用Spring的classpath:
前綴。
請注意,Spring對WebApplicationContext
實現的測試支持與其對標準ApplicationContext
實現的支持相當。使用WebApplicationContext
進行測試時,可以使用@ContextConfiguration
聲明XML配置文件、Groovy腳本或@Configuration
類。你還可以自由地使用任何其他測試註解,如@ActiveProfiles
、@Testexecutionlistener
、@Sql
、@Rollback
和其他。
本節的其餘示例展示了加載WebApplicationContext
的一些不同配置選項。以下示例顯示了TestContext
框架對配置約定的支持:
@ExtendWith(SpringExtension.class)
// defaults to "file:src/main/webapp"
@WebAppConfiguration
// detects "WacTests-context.xml" in the same package
// or static nested @Configuration classes
@ContextConfiguration
class WacTests {
//...
}
如果使用@WebAppConfiguration
註解測試類而未指定資源基本路徑,則資源路徑實際上默認為file:src/main/webapp
。同樣,如果在聲明@ContextConfiguration
時未指定資源位置、組件類或上下文初始化程序,則Spring會嘗試使用約定(也就是說,WacTests-context.xml
與WacTests
類或靜態嵌套@Configuration
類位於同一包中)。
以下示例顯示如何使用@WebAppConfiguration
顯式聲明資源基本路徑和使用@ContextConfiguration
顯式聲明XML資源位置:
@ExtendWith(SpringExtension.class)
// file system resource
@WebAppConfiguration("webapp")
// classpath resource
@ContextConfiguration("/spring/test-servlet-config.xml")
class WacTests {
//...
}
這裡要注意的重要一點是具有這兩個註解的路徑的語義不同。默認情況下,@ WebAppConfiguration
資源路徑基於文件系統,而@ContextConfiguration
資源位置基於類路徑。下面的示例顯示,我們可以通過指定Spring資源前綴來覆蓋兩個註解的默認資源語義:
@ExtendWith(SpringExtension.class)
// classpath resource
@WebAppConfiguration("classpath:test-web-resources")
// file system resource
@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")
class WacTests {
//...
}
將本示例中的註解與上一個示例進行對比。
使用Web Mock工作
為了提供全面的Web測試支持,TestContext
框架具有默認啟用的ServletTestExecutionListener
。在針對WebApplicationContext
進行測試時,此TestExecutionListener
會在每個測試方法之前使用Spring Web的RequestContextHolder
來設置默認的線程本地狀態,並根據通過@WebAppConfiguration
配置的基本資源路徑創建MockHttpServletRequest
、MockHttpServletResponse
和ServletWebRequest
。
ServletTestExecutionListener
還確保可以將MockHttpServletResponse
和ServletWebRequest
注入到測試實例中,並且一旦測試完成,它將清除線程本地狀態。
一旦為測試加載了WebApplicationContext
,你可能會發現你需要與Web模擬進行交互,例如,在調用Web組件之後設置測試fixture
或執行斷言。以下示例顯示可以將哪些模擬自動裝配到你的測試實例。請注意,WebApplicationContext
和MockServletContext
都緩存在測試套件中,而其他模擬則由ServletTestExecutionListener
針對每個測試方法進行管理。
@SpringJUnitWebConfig
class WacTests {
@Autowired
WebApplicationContext wac; // cached
@Autowired
MockServletContext servletContext; // cached
@Autowired
MockHttpSession session;
@Autowired
MockHttpServletRequest request;
@Autowired
MockHttpServletResponse response;
@Autowired
ServletWebRequest webRequest;
//...
}
上下文緩存
一旦TestContext
框架為測試加載了ApplicationContext
(或WebApplicationContext
),該上下文將被緩存並重新用於在同一測試套件中聲明相同唯一上下文配置的所有後續測試。要了解緩存的工作原理,重要的是要了解unique
和測試套件
的含義。
可以通過用於加載它的配置參數的組合來唯一標識ApplicationContext
。因此,使用配置參數的唯一組合來生成一個鍵,在該鍵下緩存上下文。TestContext
框架使用以下配置參數來構建上下文緩存鍵:
-
locations
(來自@ContextConfiguration
) -
classes
(來自@ContextConfiguration
) -
contextInitializerClasses
(來自@ContextConfiguration
) -
contextCustomizers
(來自ContextCustomizerFactory
)其中包括@DynamicPropertySource
方法,以及Spring Boot測試支持中的各種功能,例如@MockBean
和@SpyBean
。 -
contextLoader
(來自@ContextConfiguration
) -
parent
(來自@ContextHierarchy
) -
activeProfiles
(來自@ActiveProfiles
) -
propertySourceLocations
(來自@TestPropertySource
) -
propertySourceProperties
(來自@TestPropertySource
) -
resourceBasePath
(來自@WebAppConfiguration
)
例如,如果TestClassA
為@ContextConfiguration
的location
(或value
)屬性指定{“app-config.xml”,“test-config.xml”}
,則TestContext
框架將加載相應的ApplicationContext
並將其存儲在靜態上下文緩存中僅基於那些位置的key下。因此,如果TestClassB
還為其位置(通過繼承顯式或隱式)定義了{“app-config.xml”,“test-config.xml”}
,但未定義@WebAppConfiguration
、不同的ContextLoader
、不同的激活配置文件、不同的上下文初始化程序、不同的測試屬性源或不同的父上下文,則兩個測試類將共享相同的ApplicationContext
。這意味著(每個測試套件)僅需加載一次加載應用程序上下文的設置成本,並且隨後的測試執行要快得多。
測試套件和分支流程
Spring
TestContext
框架將應用程序上下文存儲在靜態緩存中。這意味著上下文實際上是存儲在靜態變量中的。換句話說,如果測試是在單獨的進程中執行的,則在每個測試執行之間都會清除靜態緩存,從而有效地禁用了緩存機制。為了從緩存機制中受益,所有測試必須在同一進程或測試套件中運行。這可以通過在IDE中以組的形式執行所有測試來實現。同樣,在使用諸如Ant、Maven或Gradle之類的構建框架執行測試時,確保該構建框架不會在測試之間進行派生(fork多個進程)很重要。例如,如果將Maven Surefire插件的forkMode設置為always或pertest,則
TestContext
框架將無法在測試類之間緩存應用程序上下文,因此,構建過程的運行速度將大大降低。
上下文緩存的大小以默認的最大32為界。只要達到最大大小,就會使用最近最少使用(LRU)驅逐策略來驅逐和關閉舊的上下文。你可以通過設置名為spring.test.context.cache.maxSize
的JVM系統屬性,從命令行或構建腳本中配置最大大小。或者,你可以使用SpringProperties
API以編程方式設置相同的屬性。
由於在給定的測試套件中加載大量的應用程序上下文會導致該套件花費不必要的長時間來執行,因此準確地知道已加載和緩存了多少個上下文通常是有益的。要查看基礎上下文緩存的統計信息,可以將org.springframework.test.context.cache
日誌記錄類別的日誌級別設置為DEBUG
。
在不太可能的情況下,測試破壞了應用程序上下文並需要重新加載(例如,通過修改bean定義或應用程序對象的狀態),你可以使用@DirtiesContext
註解測試類或測試方法(請參閱@DirtiesContext
中對@DirtiesContext的討論)。這指示Spring在運行需要相同應用程序上下文的下一個測試之前,從緩存中刪除上下文並重建應用程序上下文。請注意,默認情況下啟用的DirtiesContextBeforeModesTestExecutionListener
和DirtiesContextTestExecutionListener
提供了對@DirtiesContext
註解的支持。
上下文層級
在編寫依賴於已加載的Spring ApplicationContext
的集成測試時,通常足以針對單個上下文進行測試。但是,有時需要對ApplicationContext
實例的層次結構進行測試是有益的,甚至是必要的。例如,如果你正在開發Spring MVC Web應用程序,則通常由Spring的ContextLoaderListener
加載根WebApplicationContext
,由Spring的DispatcherServlet
加載子WebApplicationContext
。這將導致父子上下文層次結構,其中共享組件和基礎設施配置在根上下文中聲明,並由特定於web的組件在子上下文中使用。在Spring Batch應用程序中可以找到另一個用例,在該應用程序中,你通常具有一個父上下文,該上下文為共享批處理基礎結構提供配置,而子上下文則為特定批處理作業的配置提供配置。
你可以通過在單個測試類上或在測試類層次結構中使用@ContextHierarchy
註解聲明上下文配置來編寫使用上下文層次結構的集成測試。如果在測試類層次結構中的多個類上聲明瞭上下文層次結構,則還可以合併或覆蓋上下文層次結構中特定命名級別的上下文配置。合併層次結構中給定級別的配置時,配置資源類型(即XML配置文件或組件類)必須一致。否則,在使用不同資源類型配置的上下文層次結構中具有不同級別是完全可以接受的。
本節中其餘的基於JUnit Jupiter的示例顯示了需要使用上下文層次結構的集成測試的常見配置方案。
具有上下文層次結構的單個測試類
ControllerIntegrationTests
通過聲明一個上下文層次結構來代表Spring MVC Web應用程序的典型集成測試場景,該上下文層次結構包含兩個級別,一個層次用於根WebApplicationContext
(通過使用TestAppConfig
@Configuration類加載),一個層次用於調度程序Servlet WebApplicationContext
(通過使用WebConfig
@Configuration
類加載)。自動裝配到測試實例的WebApplicationContext
是用於子上下文(即,層次結構中的最低上下文)的WebApplicationContext
。
以下清單顯示了此配置方案:
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(classes = TestAppConfig.class),
@ContextConfiguration(classes = WebConfig.class)
})
class ControllerIntegrationTests {
@Autowired
WebApplicationContext wac;
// ...
}
參考代碼:
org.liyong.test.annotation.test.spring.ControllerIntegrationTests
具有隱式父上下文的類層次結構
本示例中的測試類在測試類層次結構中定義了上下文層次結構。AbstractWebTests
在Spring驅動的Web應用程序中聲明根WebApplicationContext
的配置。但是請注意,AbstractWebTests
不會聲明@ContextHierarchy
。因此,AbstractWebTests
的子類可以選擇參與上下文層次結構或遵循@ContextConfiguration
的標準語義。SoapWebServiceTests
和RestWebServiceTests
都擴展了AbstractWebTests
並使用@ContextHierarchy
定義了上下文層次結構。結果是,加載了三個應用程序上下文(每個@ContextConfiguration
聲明一個),並且基於AbstractWebTests
中的配置加載的應用程序上下文被設置為具體子類加載的每個上下文的父上下文。
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml")
public abstract class AbstractWebTests {}
@ContextHierarchy(@ContextConfiguration("/spring/soap-ws-config.xml"))
public class SoapWebServiceTests extends AbstractWebTests {}
@ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml"))
public class RestWebServiceTests extends AbstractWebTests {}
參考代碼:
org.liyong.test.annotation.test.spring.RestWebServiceTests
合併上下文層次結構配置的類層次結構
此示例中的類顯示了使用命名層次結構級別的目的,以及合併上下文層次結構中特定級別的配置。BaseTests
在層次結構中定義了兩個級別,parent
和child
。ExtendedTests
擴展BaseTests
並指示Spring TestContext
框架合併子層次結構級別的上下文配置,方法是確保在@ContextConfiguration
的name屬性中聲明的名稱均為子元素。結果是加載了三個應用程序上下文:一個用於/app-config.xml
、一個用於/user-config.xml
、一個用於{/user-config.xml
,/order-config.xml}
。與前面的示例一樣,將從/app-config.xml
加載的應用程序上下文設置為從/user-config.xml
和{“/user-config.xml","/order-config.xml“}
加載的上下文的父上下文(合併配置文件)。以下清單顯示了此配置方案:
@ExtendWith(SpringExtension.class)
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "/app-config.xml"),
@ContextConfiguration(name = "child", locations = "/user-config.xml")
})
class BaseTests {}
@ContextHierarchy(
@ContextConfiguration(name = "child", locations = "/order-config.xml")
)
class ExtendedTests extends BaseTests {}
參考代碼:
org.liyong.test.annotation.test.spring.ExtendedTests
具有覆蓋的上下文層次結構配置的類層次結構
與前面的示例相反,此示例演示瞭如何通過將@ContextConfiguration
中的InheritLocations
標誌設置為false
來覆蓋上下文層次結構中給定命名級別的配置。因此,ExtendedTests
的應用程序上下文僅從/test-user-config.xml
加載,並且其父級設置為從/app-config.xml
加載的上下文。以下清單顯示了此配置方案:
@ExtendWith(SpringExtension.class)
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "/app-config.xml"),
@ContextConfiguration(name = "child", locations = "/user-config.xml")
})
class BaseTests {}
@ContextHierarchy(
@ContextConfiguration(
name = "child",
locations = "/test-user-config.xml",
inheritLocations = false
))
class ExtendedTests extends BaseTests {}
清除上下文層次結構中的上下文
如果你在一個測試中使用@DirtiesContext,該測試的上下文被配置為上下文層次結構的一部分,那麼你可以使用hierarchyMode標誌來控制如何清除上下文緩存。有關更多詳細信息,請參見Spring Testing Annotations中的@DirtiesContext和@DirtiesContext javadoc的討論。
參考代碼:
org.liyong.test.annotation.test.spring.ExtendedTests1
3.5.6 測試裝置的依賴注入
當使用DependencyInjectionTestExecutionListener
(默認配置)時,測試實例的依賴項是從使用@ContextConfiguration
或相關注解配置應用程序上下文中的bean注入的。你可以使用setter
注入、字段注入、或同時使用這兩種方法,具體取決於你選擇的註解以及是否將它們放在setter
方法或字段上。如果你使用的是JUnit Jupiter,則還可以選擇使用構造函數注入(請參閱帶有SpringExtension的依賴注入)。為了與Spring基於註解的注入支持保持一致,你還可以將Spring的@Autowired
註解或JSR-330中的@Inject
註解用於字段注入和setter 注入。
對於JUnit Jupiter以外的測試框架,
TestContext
框架不參與測試類的實例化。因此,將@Autowired
或@Inject
用於構造函數對測試類無效。儘管在生產代碼中不鼓勵使用字段注入,但是在測試代碼中字段注入實際上是很自然的。理由是你永遠不會直接實例化測試類。因此,不需要在測試類上調用公共構造函數或
setter
方法。
因為@Autowired
用於按類型執行自動裝配,所以如果你具有多個相同類型的Bean定義,那麼對於那些特定的Bean,你將不能依靠這種方法。在這種情況下,可以將@Autowired
與@Qualifier
結合使用。你也可以選擇將@Inject
與@Named
結合使用。或者,如果你的測試類可以訪問其ApplicationContext
,則可以通過使用(例如)對applicationContext.getBean(“ titleRepository“,TitleRepository.class)
的調用來執行顯式查找。
如果你不希望將依賴項注入應用於測試實例,請不要使用@Autowired
或@Inject
註解字段或設置器方法。或者,你可以通過顯式地用@TestExecutionListeners
配置你的類,並從監聽器列表中忽略DependencyInjectionTestExecutionListener.class
來禁用依賴注入。
考慮測試HibernateTitleRepository
類的場景,如目標部分所述。接下來的兩個代碼清單演示了@Autowired
在字段和setter
方法上的用法。在所有示例代碼清單之後顯示了應用程序上下文配置。
以下代碼清單中的依賴項注入行為並非特定於JUnit Jupiter。相同的
DI
技術可以與任何受支持的測試框架結合使用。以下示例對靜態斷言方法(例如
assertNotNull()
)進行了調用,但沒有在聲明前添加Assertions
。在這種情況下,假定該方法是通過示例中未顯示的import static
聲明正確導入的。
第一個代碼清單顯示了使用@Autowired
進行字段注入的測試類的基於JUnit Jupiter的實現:
@ExtendWith(SpringExtension.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration("repository-config.xml")
class HibernateTitleRepositoryTests {
// this instance will be dependency injected by type
@Autowired
HibernateTitleRepository titleRepository;
@Test
void findById() {
Title title = titleRepository.findById(new Long(10));
assertNotNull(title);
}
}
或者,你可以將類配置為使用@Autowired
進行setter
注入,如下所示:
@ExtendWith(SpringExtension.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration("repository-config.xml")
class HibernateTitleRepositoryTests {
// this instance will be dependency injected by type
HibernateTitleRepository titleRepository;
@Autowired
void setTitleRepository(HibernateTitleRepository titleRepository) {
this.titleRepository = titleRepository;
}
@Test
void findById() {
Title title = titleRepository.findById(new Long(10));
assertNotNull(title);
}
}
前面的代碼清單使用@ContextConfiguration
註解引用的相同XML上下文文件(即,repository-config.xml
)。下面顯示了此配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- this bean will be injected into the HibernateTitleRepositoryTests class -->
<bean id="titleRepository" class="com.foo.repository.hibernate.HibernateTitleRepository">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- configuration elided for brevity -->
</bean>
</beans>
如果你是從Spring提供的測試基類擴展而來的,而該基類恰巧在其
setter
方法之一上使用@Autowired
,則可能在應用程序上下文中定義了多個受影響類型的Bean(例如,多個DataSource
Bean)。在這種情況下,你可以覆蓋setter方法,並使用@Qualifier
註解指示特定的目標bean,如下所示(但請確保也委託給超類中的重寫方法):// ... @Autowired @Override public void setDataSource(@Qualifier("myDataSource") DataSource dataSource) { super.setDataSource(dataSource); } // ...
指定的限定符值指示要注入的特定
DataSource
Bean,從而將類型匹配的範圍縮小到特定Bean。其值與相應的定義中的聲明匹配。Bean名稱用作後備限定符值,因此你也可以在該名稱中有效地指向特定的Bean(如先前所示,假設myDataSource
是BeanID
)。
作者
個人從事金融行業,就職過易極付、思建科技、某網約車平臺等重慶一流技術團隊,目前就職於某銀行負責統一支付系統建設。自身對金融行業有強烈的愛好。同時也實踐大數據、數據存儲、自動化集成和部署、分佈式微服務、響應式編程、人工智能等領域。同時也熱衷於技術分享創立公眾號和博客站點對知識體系進行分享。關注公眾號:青年IT男 獲取最新技術文章推送!
博客地址: http://youngitman.tech
CSDN: https://blog.csdn.net/liyong1028826685
微信公眾號:
技術交流群: