We will start with What Spring Configuration annotation is and create a java configuration file for the project and pragmatically instantiate a container.
Previous post
@Configuration
annotation?@Configuration
annotation indicates that there is one or more bean methods and spring containers can process to generate bean definitions at runtime. Also, @Bean
annotation is used at method level to signifies that this will be registered as bean in spring context. Let's create a quick configuration class.
@Configuration
public class WelcomeGbConfig {
@Bean
GreetingService greetingService() {
return new GreetingService();
}
}
Now, we will create spring context as follows.
// using try with resources so that this context closes automatically
try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
WelcomeGbConfig.class);) {
GreetingService greetingService = context.getBean(GreetingService.class);
greetingService.greet();
}
greet()
on bean object.This is how you can use configuration file (Java based) to define bean and being processed by spring context. You can also find the full example code on Github.