// Define bean for our sad fortune service @Bean public FortuneService sadFortuneService(){ // method name is the BeanId returnnew SadFortuneService(); }
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. returnnew SwimCoach(sadFortuneService()); }
Read Spring Java Configuration class
1 2 3
// read spring config java class AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SportConfig.class);
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; }
@Bean - The @Bean annotation tells Spring that we are creating a bean component manually. The default scope is singleton.
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.
SwimCoach mySwimCoach = new SwimCoach(); - This code will create a new instance of the SwimCoach.
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
Create Properties File
Load Properties File in Spring config
Reference value from Properties File
Reference: Udemy, Spring & Hibernate for Beginners (including SpringBoot)