Spring Framework - A Java configuration for Spring

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

1. What is @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();
}
  1. we created the spring context.
  2. We got the bean from context.
  3. We call 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.



Tags: Spring Framework, Spring Core, Spring Context, Spring Java Configuration example

← Back home