@RunWith(SpringJUnit4ClassRunner.class)、@ ContextConfiguration的意思
@ContextConfiguration
この注釈は、一般@RunWith(SpringJUnit4ClassRunner.class)
の併用を試験するために使用します
クラスがコメントを追加すると@Component
、その後、彼は自動的に設定されているSpring構成ファイルを表示する必要はありません、豆になります。これらのBeanには、2つの方法、JavaとXMLの方法のように通常収集します。これらのBeanが収集したとき、我々はテストクラスで使用する場合、@Autowired
これらのアップを収集するために豆の注釈を導入したとき、ちょうど追加するには、このテストクラスを与え@ContextConfiguration
、我々はテストクラスの一部をインポートするBeanをマークするために注釈を。
XML
高齢者のための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" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd > <!-- 自动扫描该包 --> <context:component-scan base-package="com" /> </beans>
このXMLファイル<context:component-scan base-package="com" />
豆袋コムの下のラベルが自動的にすべての着信をスキャンします。
ここでは、テストすることができるようになります。
一般的な書き込み:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/*.xml"})
public class CDPlayerTest { }
@ContextConfiguration
ブラケットlocations = {"classpath*:/*.xml"}
、すべての.xmlファイル内のクラスパスは、先ほど作成したXMLファイルが含まれますので、それは自動的に、あなたはクラスでテストすることができ、あなたが得ることができる豆の内部をスキャン、含まれていると言います使用@Autowired
すべてのBeanを取得するには、注釈の前にパッケージの下に自動スキャンを
classpath和classpath*区别:
-
クラスパス:ファイルのみを見つけるためにあなたのクラスパスを見つけます。
-
クラスパス*:それはまた、それを見つけるためにjarファイル(クラスパス)が含まれ、だけでなく、クラスパスを含んでいます。
@ComponentScan
あなたは非常にシンプルになりますJavaの道を使用している場合、我々は、上記のみ、このクラスに追加する必要があり、我々は代わりにXMLファイルのJavaクラスを作成することができますので、複雑な書き込みXML文書にはありません@Configuration
、その後、追加のコメント@ComponentScan
オープンに注釈を自動スキャン、ノートは括弧内の書き込みものしなかった場合は、同じ@ ComponentScanデフォルトスキャン設定クラスパッケージ。
@Configuration
@ComponentScan
public class CDPlayConfig { }
あなたはそれをテストしたい場合は、この時点で、あなたは書くことができます。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayConfig.class)
public class CDPlayerTest { }
XMLと比較すると、それは仕方の公式の提唱者である、非常にクールではありません。
春ブーツ試験で
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class Test { }
注釈@SpringBootTest SpringBootは、メインクラス豆に導入されたことを、この手段は全て含まれています。
このときSpringBootメインクラスはまた、コレクタBeanとして使用されます。上記同様CDPlayConfig。
@SpringBootApplication
@SpringBootConfiguration
@ComponentScan(basePackages = {"com.bihang.*"})
public class CarOrderWebApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(CarOrderWebApplication.class); } public static void main(String[] args) { SpringApplication.run(CarOrderWebApplication.class, args); } }
转自:https://www.cnblogs.com/bihanghang/p/10023759.html