使用 AnnotationConfigApplicationContext 例項化 Spring 容器

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

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

@Component 和 JSR-330 類作為輸入時,它們被註冊為 bean 定義,並且假定在這些類中必要時使用 @Autowired@Inject 等 DI 元資料。

簡單構造

與例項化 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 應用程式

AnnotationConfigApplicationContextWebApplicationContext 變體可透過 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。
© . This site is unofficial and not affiliated with VMware.