Spring AnnotationConfigApplicationContext Example
November 16, 2021
On this page we will learn using Spring AnnotationConfigApplicationContext
class.
1. The
AnnotationConfigApplicationContext
is the standalone application context that accepts @Configuration
classes as well as plain @Component
classes.
2. It also accepts JSR-330 compliant classes using
javax.inject
annotations.
3. We can register classes using
register(Class<?>...)
method or can scan a specified base package using scan(String...)
method.
4. In case of multiple
@Configuration
classes, the @Bean
methods defined in later classes will override those defined in earlier classes.
5. The
AnnotationConfigApplicationContext
is introduced in Spring 3.0.
The
AnnotationConfigApplicationContext
has following methods.
register: Register one or more
@component
classes or @Configuration
classes.
registerBean: Register a bean from the given bean class, using the given supplier for obtaining a new instance.
scan: Perform a scan within the specified base package.
setBeanNameGenerator: Sets a custom
BeanNameGenerator
.
setEnvironment: Propagate the given custom Environment.
setScopeMetadataResolver: Set the
ScopeMetadataResolver
to use for registered component classes.
With @Configuration
AppTest.javapackage com.concretepage; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class AppTest { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); Entitlement ent= (Entitlement)ctx.getBean("entitlement"); System.out.println(ent.getName()); System.out.println(ent.getTime()); } }
package com.concretepage; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean(name="entitlement") public Entitlement entitlement(){ Entitlement ent= new Entitlement(); ent.setName("Entitlement"); ent.setTime(20); return ent; } }
package com.concretepage; public class Entitlement { private String name; private int time; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } }