使用 AnnotationConfigApplicationContext 實例化 Spring 容器

以下章節說明 Spring 3.0 中引入的 Spring AnnotationConfigApplicationContext。這個多功能的 ApplicationContext 實作不僅可以接受 @Configuration 類別作為輸入,還可以接受純 @Component 類別和使用 JSR-330 metadata 註解的類別。

當提供 @Configuration 類別作為輸入時,@Configuration 類別本身會註冊為 bean 定義,並且類別中所有宣告的 @Bean 方法也會註冊為 bean 定義。

當提供 @Component 和 JSR-330 類別時,它們會註冊為 bean 定義,並且假設在這些類別中必要時使用了 DI metadata,例如 @Autowired@Inject

簡單建構

就像在實例化 ClassPathXmlApplicationContext 時使用 Spring XML 檔案作為輸入一樣,您可以在實例化 AnnotationConfigApplicationContext 時使用 @Configuration 類別作為輸入。這樣可以完全免 XML 的使用 Spring 容器,如下列範例所示

  • Java

  • Kotlin

public static void main(String[] args) {
	ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
	MyService myService = ctx.getBean(MyService.class);
	myService.doStuff();
}
import org.springframework.beans.factory.getBean

fun main() {
	val ctx = AnnotationConfigApplicationContext(AppConfig::class.java)
	val myService = ctx.getBean<MyService>()
	myService.doStuff()
}

如先前所述,AnnotationConfigApplicationContext 不僅限於僅使用 @Configuration 類別。任何 @Component 或 JSR-330 註解的類別都可以作為建構子的輸入提供,如下列範例所示

  • Java

  • Kotlin

public static void main(String[] args) {
	ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class, Dependency2.class);
	MyService myService = ctx.getBean(MyService.class);
	myService.doStuff();
}
import org.springframework.beans.factory.getBean

fun main() {
	val ctx = AnnotationConfigApplicationContext(MyServiceImpl::class.java, Dependency1::class.java, Dependency2::class.java)
	val myService = ctx.getBean<MyService>()
	myService.doStuff()
}

前面的範例假設 MyServiceImplDependency1Dependency2 使用 Spring 相依性注入註解,例如 @Autowired

透過程式設計方式使用 register(Class<?>…​) 建構容器

您可以使用無引數建構子實例化 AnnotationConfigApplicationContext,然後使用 register() 方法組態它。當以程式設計方式建構 AnnotationConfigApplicationContext 時,此方法特別有用。下列範例說明如何執行此操作

  • Java

  • Kotlin

public static void main(String[] args) {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(AppConfig.class, OtherConfig.class);
	ctx.register(AdditionalConfig.class);
	ctx.refresh();
	MyService myService = ctx.getBean(MyService.class);
	myService.doStuff();
}
import org.springframework.beans.factory.getBean

fun main() {
	val ctx = AnnotationConfigApplicationContext()
	ctx.register(AppConfig::class.java, OtherConfig::class.java)
	ctx.register(AdditionalConfig::class.java)
	ctx.refresh()
	val myService = ctx.getBean<MyService>()
	myService.doStuff()
}

使用 scan(String…​) 啟用元件掃描

若要啟用元件掃描,您可以如下所示註解您的 @Configuration 類別

  • Java

  • Kotlin

@Configuration
@ComponentScan(basePackages = "com.acme") (1)
public class AppConfig  {
	// ...
}
1 此註解啟用元件掃描。
@Configuration
@ComponentScan(basePackages = ["com.acme"]) (1)
class AppConfig  {
	// ...
}
1 此註解啟用元件掃描。

經驗豐富的 Spring 使用者可能熟悉 Spring context: namespace 中的等效 XML 宣告,如下列範例所示

<beans>
	<context:component-scan base-package="com.acme"/>
</beans>

在前面的範例中,掃描 com.acme 套件以尋找任何 @Component 註解的類別,並且這些類別在容器中註冊為 Spring bean 定義。AnnotationConfigApplicationContext 公開 scan(String…​) 方法,以允許相同的元件掃描功能,如下列範例所示

  • Java

  • Kotlin

public static void main(String[] args) {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.scan("com.acme");
	ctx.refresh();
	MyService myService = ctx.getBean(MyService.class);
}
fun main() {
	val ctx = AnnotationConfigApplicationContext()
	ctx.scan("com.acme")
	ctx.refresh()
	val myService = ctx.getBean<MyService>()
}
請記住,@Configuration 類別使用 @Component 進行了 meta-annotation,因此它們是元件掃描的候選者。在前面的範例中,假設 AppConfigcom.acme 套件(或任何底下的套件)中宣告,則在呼叫 scan() 期間會被選取。在 refresh() 時,其所有 @Bean 方法都會被處理並在容器中註冊為 bean 定義。

使用 AnnotationConfigWebApplicationContext 支援 Web 應用程式

WebApplicationContextAnnotationConfigApplicationContext 變體可透過 AnnotationConfigWebApplicationContext 取得。在組態 Spring ContextLoaderListener servlet 監聽器、Spring MVC DispatcherServlet 等時,可以使用此實作。下列 web.xml 片段組態典型的 Spring MVC Web 應用程式(請注意 contextClass context-param 和 init-param 的使用)

<web-app>
	<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
		instead of the default XmlWebApplicationContext -->
	<context-param>
		<param-name>contextClass</param-name>
		<param-value>
			org.springframework.web.context.support.AnnotationConfigWebApplicationContext
		</param-value>
	</context-param>

	<!-- Configuration locations must consist of one or more comma- or space-delimited
		fully-qualified @Configuration classes. Fully-qualified packages may also be
		specified for component-scanning -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>com.acme.AppConfig</param-value>
	</context-param>

	<!-- Bootstrap the root application context as usual using ContextLoaderListener -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Declare a Spring MVC DispatcherServlet as usual -->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
			instead of the default XmlWebApplicationContext -->
		<init-param>
			<param-name>contextClass</param-name>
			<param-value>
				org.springframework.web.context.support.AnnotationConfigWebApplicationContext
			</param-value>
		</init-param>
		<!-- Again, config locations must consist of one or more comma- or space-delimited
			and fully-qualified @Configuration classes -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>com.acme.web.MvcConfig</param-value>
		</init-param>
	</servlet>

	<!-- map all requests for /app/* to the dispatcher servlet -->
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/app/*</url-pattern>
	</servlet-mapping>
</web-app>
對於程式設計使用案例,可以使用 GenericWebApplicationContext 作為 AnnotationConfigWebApplicationContext 的替代方案。請參閱 GenericWebApplicationContext javadoc 以取得詳細資訊。