SPRING IN ACTION 第4版笔记-第一章-002-DI介绍

时间:2023-03-08 15:35:22
SPRING IN ACTION 第4版笔记-第一章-002-DI介绍

一、

1.knight.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="knight" class="chapter01.sia.knights.BraveKnight">
<constructor-arg ref="quest" />
</bean> <bean id="quest" class="chapter01.sia.knights.SlayDragonQuest">
<constructor-arg value="#{T(System).out}" />
</bean> </beans>

2.Knight

 package chapter01.sia.knights;

 public interface Knight {

   void embarkOnQuest();

 }

3.BraveKnight

 package chapter01.sia.knights;

 public class BraveKnight implements Knight {

   private Quest quest;

   public BraveKnight(Quest quest) {
this.quest = quest;
} public void embarkOnQuest() {
quest.embark();
} }

4.SlayDragonQuest

 package chapter01.sia.knights;

 import java.io.PrintStream;

 public class SlayDragonQuest implements Quest {

   private PrintStream stream;

   public SlayDragonQuest(PrintStream stream) {
this.stream = stream;
} public void embark() {
stream.println("Embarking on quest to slay the dragon!");
} }

5.

 package chapter01.sia.knights;

 import org.springframework.context.support.
ClassPathXmlApplicationContext; public class KnightMain { public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("classpath:knight.xml");
Knight knight = context.getBean(Knight.class);
knight.embarkOnQuest();
context.close();
} }

6.运行

 三月 01, 2016 9:42:47 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4ec12ad8: startup date [Tue Mar 01 09:42:47 CST 2016]; root of context hierarchy
三月 01, 2016 9:42:47 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [knight.xml]
三月 01, 2016 9:42:47 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@4ec12ad8: startup date [Tue Mar 01 09:42:47 CST 2016]; root of context hierarchy
Embarking on quest to slay the dragon!