zoukankan      html  css  js  c++  java
  • 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!

  • 相关阅读:
    CI框架主题切换的功能
    centos7 编译安装 php7.4
    单用户登陆demo-后者挤到前者,类似QQ
    nginx 负载均衡的配置
    PHP计算每月几周,每周的开始结束日期
    Centos7 编译安装PHP7
    TP 3.2.3 接入PHPMailer
    外部js引用vue实例环境的方式
    linux常用命令
    计算机中的二级制
  • 原文地址:https://www.cnblogs.com/shamgod/p/5230533.html
Copyright © 2011-2022 走看看