Section 10 Flashcards
How a java class can be used instead of applicationContext.xml file configuration file ?
@Configuration
@ComponentScan(“com.mycompany.springdemo”)
public class SportConfig {
}
Create a application using java code configuration.
Output:
Swim workout
Sad fortune service
//Main public static void main(String[] args) {
AnnotationConfigApplicationContext container = new AnnotationConfigApplicationContext(SportConfig.class); Coach coach = container.getBean("swimCoach", Coach.class); System.out.println(coach.getDailyWorkout()); System.out.println(coach.getDailyFortune()); container.close(); }
//SadFortuneService
public class SadFortuneService implements FortuneService {
@Override public String getFortune() { return "Sad fortune service"; }
}
//SportConfig
@Configuration public class SportConfig {
@Bean public FortuneService sadFortuneService() { return new SadFortuneService(); }
@Bean public Coach swimCoach() { return new SwimCoach(sadFortuneService()); }
}
//SwimCoach public class SwimCoach implements Coach {
private FortuneService fortuneService;
public SwimCoach(FortuneService fortuneService) { this.fortuneService = fortuneService; }
@Override public String getDailyWorkout() { return "Swim workout"; } @Override public String getDailyFortune() { return fortuneService.getFortune(); }
}
Incarcati intr-un fisier de configurare java, un fisier sport.properties care contine urmatoarele valori:
email=raduadyi@yahoo.com-loaded-from-a-file
team= a swim team-loaded-from-a-file
Preluati valorile in clasa SwimCoach si afisati valorile in output
//SportConfig file
@Configuration
@PropertySource(“file:src/main/java/com/mycompany/springdemo/sport.properties”)
public class SportConfig {
@Bean public FortuneService sadFortuneService() { return new SadFortuneService(); }
@Bean public Coach swimCoach() { return new SwimCoach(sadFortuneService()); }
}
//Main public class Main {
public static void main(String[] args) { AnnotationConfigApplicationContext container = new AnnotationConfigApplicationContext(SportConfig.class); SwimCoach coach = container.getBean("swimCoach", SwimCoach.class); System.out.println(coach.getEmail()); System.out.println(coach.getTeam()); container.close(); }
}
//SwimCoach class
public class SwimCoach implements Coach {
@Value("${email}") private String email; @Value("${team}") private String team; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } }