一、

1.

 package chapter01.sia.knights.config;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import chapter01.sia.knights.BraveKnight;
import chapter01.sia.knights.Knight;
import chapter01.sia.knights.Quest;
import chapter01.sia.knights.SlayDragonQuest; @Configuration
public class KnightConfig { @Bean
public Knight knight() {
return new BraveKnight(quest());
} @Bean
public Quest quest() {
return new SlayDragonQuest(System.out);
} }

解析:

(1)public Knight knight() {

return new BraveKnight(quest());
}  说明new knight时用BraveKnight

(2)@Bean

public Quest quest() {
return new SlayDragonQuest(System.out);
}  说明new quest时用SlayDragonQuest

 package chapter01.sia.knights;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class KnightMain { public static void main(String[] args) throws Exception {
//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:knight.xml");
//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:minstrel.xml");
ApplicationContext context = new AnnotationConfigApplicationContext(
chapter01.sia.knights.config.KnightConfig.class);
Knight knight = context.getBean(Knight.class);
knight.embarkOnQuest();
//context.close();
} }

运行

Embarking on quest to slay the dragon!

05-11 10:49