使用 AnnotationConfigApplicationContext 例項化 Spring 容器

以下章節介紹了 Spring 的 AnnotationConfigApplicationContext,該類在 Spring 3.0 中引入。這個多功能的 ApplicationContext 實現不僅可以接受 @Configuration 類作為輸入,還可以接受普通的 @Component 類和使用 JSR-330 元資料標註的類。

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

當提供 @Component 和 JSR-330 類時,它們被註冊為 Bean 定義,並且假設在這些類中必要時使用了 @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: 名稱空間中等效的 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 元註解進行了標註,因此它們是元件掃描的候選物件。在前面的示例中,假設 AppConfig 宣告在 com.acme 包(或其下的任何包)內,它將在呼叫 scan() 期間被掃描到。在呼叫 refresh() 後,其所有 @Bean 方法都會被處理並註冊為容器中的 Bean 定義。

使用 AnnotationConfigWebApplicationContext 支援 Web 應用

AnnotationConfigApplicationContext 的一個 WebApplicationContext 變體是 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。