Learnitweb

AnnotationConfigApplicationContext in Spring

1. Introduction

Spring Container can be instantiated using AnnotationConfigApplicationContext. AnnotationConfigApplicationContext was introduced in Spring 3.0. AnnotationConfigApplicationContext is an implementation of ApplicationContext.

This accepts @Configuration classes, @Component classes and classes annotated with JSR-330 metadata.

When @Configuration classes are supplied, the @Configuration class is registered as a bean definition, and all its declared @Bean methods are also registered as separate bean definitions. When @Component and JSR-330 classes are provided, they are registered as bean definitions, with the assumption that dependency injection metadata like @Autowired or @Inject is used within those classes where needed.

2. Construction

Here is an example of creating AnnotationConfigApplicationContext with @Configuration class. Here supplied class AppConfig is a class annotated with @Configuration:

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

Here is an example of AnnotationConfigApplicationContext working with JSR-330 annotated class.

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

3. Building the container programmatically

You can instantiate an AnnotationConfigApplicationContext by using a no-arg constructor and then configure it by using the register() method. Here is an example:

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

To enable To enable component scanning, you can annotate your @Configuration class with @ComponentScan. Here is an example:

@Configuration
@ComponentScan(basePackages = "com.learnitweb")
public class AppConfig  {
	// ...
}

4. Conclusion

In conclusion, the AnnotationConfigApplicationContext in Spring provides a powerful and flexible way to configure and manage your application context using annotations. By leveraging @Configuration classes and @Bean methods, you can define and manage beans with ease. Additionally, support for @Component and JSR-330 annotations allows for seamless dependency injection, ensuring that your application components are properly wired and managed by the Spring IoC container. This approach promotes a clean, maintainable, and scalable architecture for your Spring applications.