Configure with Java Code

Last Updated on: January 13, 2021 pm

Configure with Java Code

  1. Create a Java Class and annotate as @Configuration
  2. Add Component scanning support: @ComponentScan (Optional)
  3. Read Spring Java configuration class
  4. Retrieve bean from Spring container

Define Beans with Java Code

  1. Define method to expose bean
1
2
3
4
5
6
// Define bean for our sad fortune service
@Bean
public FortuneService sadFortuneService(){
// method name is the BeanId
return new SadFortuneService();
}
  1. Injection bean dependencies
1
2
3
4
5
6
@Bean
// Define bean for swim coach and inject dependency
public Coach swimCoach(){
// injection sadFortuneService to the swim coach as a dependency.
return new SwimCoach(sadFortuneService());
}
  1. Read Spring Java Configuration class
1
2
3
// read spring config java class
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(SportConfig.class);
  1. Retrieve bean from Spring container
1
2
// get the bean from spring container
Coach theCoach = context.getBean("swimCoach", Coach.class);

How @Bean works behind the scenes

1
2
3
4
5
@Bean 
public Coach swimCoach() {
SwimCoach mySwimCoach = new SwimCoach();
return mySwimCoach;
}
  1. @Bean - The @Bean annotation tells Spring that we are creating a bean component manually. The default scope is singleton.
  2. public Coach swimCoach() { - This specifies that the bean will bean id of “swimCoach”. The return type is the Coach interface. This can help Spring find any dependencies that implement the Coach interface.
  3. SwimCoach mySwimCoach = new SwimCoach(); - This code will create a new instance of the SwimCoach.
  4. return mySwimCoach; - This code return a instance of the swimCoach.

This code is only executed once during the initial bean creation since it is singleton scope.

Inject Value from a Properties File

  1. Create Properties File
  2. Load Properties File in Spring config
  3. Reference value from Properties File

Reference: Udemy, Spring & Hibernate for Beginners (including SpringBoot)