Spring. Defining Spring Beans with Java Code (no XML)
package com.example.demo;
public interface FortuneService {
public String getFortune();
}
package com.example.demo;
public class SadFortuneService implements FortuneService{
@Override
public String getFortune() {
return "Today is a sad day";
}
}package com.example.demo;
public interface Coach {
public String getDailyWorkout();
public String getDailyFortune();
}package com.example.demo;
public class SwimCoach implements Coach {
private FortuneService fortuneService;
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();
}
}package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
//@ComponentScan("com.example.demo")
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.context.annotation.AnnotationConfigApplicationContext;
public class SwimJavaConfigDemoApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SportConfig.class);
Coach coach = context.getBean("swimCoach", Coach.class);
System.out.println(coach.getDailyWorkout());
System.out.println(coach.getDailyFortune());
context.close();
}
}
Комментарии
Отправить комментарий