File tree Expand file tree Collapse file tree 5 files changed +26
-1
lines changed Expand file tree Collapse file tree 5 files changed +26
-1
lines changed Original file line number Diff line number Diff line change 33import org .springframework .context .annotation .Bean ;
44import org .springframework .context .annotation .ComponentScan ;
55import org .springframework .context .annotation .Configuration ;
6+ import org .springframework .context .annotation .PropertySource ;
67
78@ Configuration
89@ ComponentScan ("com.luv2code.springdemo" )
10+ @ PropertySource ("classpath:sport.properties" )
911public class SportConfig {
1012
1113 @ Bean
Original file line number Diff line number Diff line change 11package com .luv2code .springdemo ;
22
3+ import org .springframework .beans .factory .annotation .Value ;
4+
35public class SwimCoach implements Coach {
46
57 private FortuneService fortuneService ;
68
9+ @ Value ("${foo.email}" )
10+ private String email ;
11+
12+ @ Value ("${foo.team}" )
13+ private String team ;
14+
715 public SwimCoach (FortuneService fortuneService ) {
816 this .fortuneService = fortuneService ;
917 }
@@ -17,4 +25,12 @@ public String getDailyWorkout() {
1725 public String getDailyFortune () {
1826 return fortuneService .getFortune ();
1927 }
28+
29+ public String getEmail () {
30+ return email ;
31+ }
32+
33+ public String getTeam () {
34+ return team ;
35+ }
2036}
Original file line number Diff line number Diff line change @@ -10,11 +10,14 @@ public static void main(String[] args) {
1010 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (SportConfig .class );
1111
1212// Retrieve the bean from Spring container
13- Coach coach = context .getBean ("swimCoach" , Coach .class );
13+ // Using SwimCoach instead of Coach just to use getEmail, getTeam
14+ SwimCoach coach = context .getBean ("swimCoach" , SwimCoach .class );
1415
1516// Call methods on the bean
1617 System .out .println (coach .getDailyWorkout ());
1718 System .out .println (coach .getDailyFortune ());
19+ System .out .println (coach .getEmail ());
20+ System .out .println (coach .getTeam ());
1821
1922// Close the context
2023 context .close ();
Original file line number Diff line number Diff line change @@ -30,6 +30,8 @@ Spring Annotations
3030 It eliminates xml config file altogether.
3131 -> @ComponentScan - Tells Spring to look for all beans inside the package
3232 @ComponentScan("com.gemalto.archit")
33+ -> @PropertySource- To inject values from properties file @PropertySource("classpath:sport.properties")
34+ -> @Value - To inject values from properties file @Value("${foo.email}")
3335 -> @Bean - To create bean inside the configuration class with @Configuration
3436 -> @Scope - Defines bean scope (Default:Singleton)
3537 -> @PostConstruct - Bean lifecycle
Original file line number Diff line number Diff line change 1+ foo.email =abc@gmail.com
2+ foo.team =myTeam
You can’t perform that action at this time.
0 commit comments