SPRING IN ACTION 第4版笔记-第一章-004-用类来管理DI

一、

1.

 1 package chapter01.sia.knights.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 import chapter01.sia.knights.BraveKnight;
 7 import chapter01.sia.knights.Knight;
 8 import chapter01.sia.knights.Quest;
 9 import chapter01.sia.knights.SlayDragonQuest;
10 
11 @Configuration
12 public class KnightConfig {
13 
14   @Bean
15   public Knight knight() {
16     return new BraveKnight(quest());
17   }
18   
19   @Bean
20   public Quest quest() {
21     return new SlayDragonQuest(System.out);
22   }
23 
24 }

解析:

(1)public Knight knight() {

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

(2)@Bean

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

 1 package chapter01.sia.knights;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 5 
 6 public class KnightMain {
 7 
 8   public static void main(String[] args) throws Exception {
 9     //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:knight.xml");
10     //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:minstrel.xml");
11     ApplicationContext context = new AnnotationConfigApplicationContext(
12             chapter01.sia.knights.config.KnightConfig.class);
13     Knight knight = context.getBean(Knight.class);
14     knight.embarkOnQuest();
15     //context.close();
16   }
17 
18 }

运行

Embarking on quest to slay the dragon!

原文地址:https://www.cnblogs.com/shamgod/p/5230533.html