Skip to content

Commit

Permalink
evolve(annotation): java code config - inner defined bean
Browse files Browse the repository at this point in the history
  • Loading branch information
chengcyber committed Dec 27, 2017
1 parent f7f3ceb commit 667c8bb
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.luv2code.springdemo;

public class SadFortuneService implements FortuneService {

@Override
public String getFortune() {
return "Today is totaly a sad day ...";
}

}
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
package com.luv2code.springdemo;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.luv2code.springdemo")
public class SportConfig {

// define bean for our sad fortune service
@Bean
public FortuneService sadFortuneService() {
return new SadFortuneService();
}

// define bean for an swim coach AND inject dependency
@Bean
public Coach swimCoach() {
return new SwimCoach(sadFortuneService());
}

}
21 changes: 21 additions & 0 deletions spring-demo-annotations/src/com/luv2code/springdemo/SwimCoach.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.luv2code.springdemo;

public class SwimCoach implements Coach {

private FortuneService fortuneService;

public SwimCoach(FortuneService theFortuneService) {
fortuneService = theFortuneService;
}

@Override
public String getDailyWorkout() {
return "Swim 1000 meters as a warm up.";
}

@Override
public String getDailyFortune() {
return fortuneService.getFortune();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.luv2code.springdemo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SwimJavaConfigDemoApp {

public static void main(String[] args) {

// read spring config java class
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(SportConfig.class);

// get the bean from spring container
Coach theCoach = ctx.getBean("swimCoach", Coach.class);

// call a method on the bean
System.out.println(theCoach.getDailyWorkout());

// call a method with dependency injection
System.out.println(theCoach.getDailyFortune());

// close the context
ctx.close();

}

}

0 comments on commit 667c8bb

Please sign in to comment.