• 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!

  • 相关阅读:
    LeetCode278. 第一个错误的版本
    LeetCode275. H 指数 II
    LeetCode274. H 指数
    LeetCode273. 整数转换英文表示
    LeetCode268. 缺失数字
    LeetCode264. 丑数 II
    LeetCode263. 丑数
    关于解决Chrome新版本中cookie跨域携带和samesite的问题处理
    java将list转为树形结构的方法
    Python pycharm selenium hyrobot 学习中遇到的问题汇总2
  • 原文地址:https://www.cnblogs.com/shamgod/p/5230533.html
Copyright © 2020-2023  润新知