Spring. Injecting Values from Properties file.
foo.email=test@gmail.com
foo.team=test team
package com.example.demo;
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.example.demo")
@PropertySource("classpath:sport.properties")
public class SportConfig {
@Bean
public FortuneService sadFortuneService() {
return new SadFortuneService();
}
@Bean
public Coach swimCoach() {
return new SwimCoach(sadFortuneService());
}
}package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
public class SwimCoach implements Coach {
private FortuneService fortuneService;
@Value("${foo.email}")
private String email;
@Value("${foo.team}")
private String team;
public SwimCoach(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}
@Override
public String getDailyWorkout() {
return "Swim 1000 meters as a warm up.";
}
@Override
public String getDailyFortune() {
return fortuneService.getFortune();
}
public String getEmail() {
return email;
}
public String getTeam() {
return team;
}
}package com.example.demo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SwimJavaConfigDemoApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SportConfig.class);
SwimCoach coach = context.getBean("swimCoach", SwimCoach.class);
System.out.println(coach.getDailyWorkout());
System.out.println(coach.getDailyFortune());
System.out.println(coach.getTeam());
System.out.println(coach.getEmail());
context.close();
}
}
Комментарии
Отправить комментарий