Skip to content

Commit

Permalink
evolve(annotation): java code config - literal values injection
Browse files Browse the repository at this point in the history
  • Loading branch information
chengcyber committed Dec 27, 2017
1 parent 3e262ba commit dc31e4d
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,24 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ComponentScan("com.luv2code.springdemo")
@PropertySource("classpath:sport.properties")
public class SportConfig {

/* Spring 4.2 and below version need this code */
// add support to resolve ${...} properties
/*
@Bean
public static PropertySourcesPlaceholderConfigurer
propertySourcesPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
*/

// define bean for our sad fortune service
@Bean
public FortuneService sadFortuneService() {
Expand Down
16 changes: 16 additions & 0 deletions spring-demo-annotations/src/com/luv2code/springdemo/SwimCoach.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package com.luv2code.springdemo;

import org.springframework.beans.factory.annotation.Value;

public class SwimCoach implements Coach {

private FortuneService fortuneService;

/* inject value from propertysource */
@Value("${foo.email}")
private String email;
@Value("${foo.team}")
private String team;

public SwimCoach(FortuneService theFortuneService) {
fortuneService = theFortuneService;
}
Expand All @@ -18,4 +26,12 @@ public String getDailyFortune() {
return fortuneService.getFortune();
}

public String getEmail() {
return email;
}

public String getTeam() {
return team;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,18 @@ public static void main(String[] args) {
new AnnotationConfigApplicationContext(SportConfig.class);

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

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

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

// call new getter methods ... has props values injected
System.out.println("email: " + theCoach.getEmail());
System.out.println("team: " + theCoach.getTeam());

// close the context
ctx.close();

Expand Down

0 comments on commit dc31e4d

Please sign in to comment.