Skip to content

Commit 45472a6

Browse files
committed
constructor injection
1 parent 4a2d7c3 commit 45472a6

5 files changed

Lines changed: 30 additions & 1 deletion

File tree

DemoAnnotation/src/main/java/code/Coach.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
public interface Coach {
44

55
public String getDailyWorkout();
6+
public String getDailyFortune();
67
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package code;
2+
3+
public interface FortuneService {
4+
public String getFortune();
5+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package code;
2+
3+
import org.springframework.stereotype.Component;
4+
5+
@Component
6+
public class HappyFortuneService implements FortuneService {
7+
8+
public String getFortune() {
9+
return "Today is your lucky day!";
10+
}
11+
12+
}

DemoAnnotation/src/main/java/code/MyApp.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ public static void main(String[] args) {
1111
// get the bean from spring container
1212
Coach theCoach = context.getBean("thatSillyCoach", Coach.class);
1313
// call a method on the bean
14-
System.out.println(theCoach.getDailyWorkout());
14+
System.out.println(theCoach.getDailyWorkout());
15+
System.out.println(theCoach.getDailyFortune());
1516
// close the context
1617
context.close();
1718
}

DemoAnnotation/src/main/java/code/TrackCoach.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
11
package code;
22

3+
import org.springframework.beans.factory.annotation.Autowired;
34
import org.springframework.stereotype.Component;
45

56
@Component("thatSillyCoach")
67
public class TrackCoach implements Coach {
8+
private FortuneService fortuneService;
9+
10+
@Autowired
11+
public TrackCoach(FortuneService theFortuneService) {
12+
fortuneService = theFortuneService;
13+
}
714
public String getDailyWorkout() {
815
return "Run a hard 5k TrackCoach";
916
}
17+
public String getDailyFortune() {
18+
return fortuneService.getFortune();
19+
}
1020

1121
}
1222

0 commit comments

Comments
 (0)