一、
1.knight.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 7 <bean id="knight" class="chapter01.sia.knights.BraveKnight"> 8 <constructor-arg ref="quest" /> 9 </bean> 10 11 <bean id="quest" class="chapter01.sia.knights.SlayDragonQuest"> 12 <constructor-arg value="#{T(System).out}" /> 13 </bean> 14 15 </beans>
2.Knight
1 package chapter01.sia.knights; 2 3 public interface Knight { 4 5 void embarkOnQuest(); 6 7 }
3.BraveKnight
1 package chapter01.sia.knights; 2 3 public class BraveKnight implements Knight { 4 5 private Quest quest; 6 7 public BraveKnight(Quest quest) { 8 this.quest = quest; 9 } 10 11 public void embarkOnQuest() { 12 quest.embark(); 13 } 14 15 }
4.SlayDragonQuest
1 package chapter01.sia.knights; 2 3 import java.io.PrintStream; 4 5 public class SlayDragonQuest implements Quest { 6 7 private PrintStream stream; 8 9 public SlayDragonQuest(PrintStream stream) { 10 this.stream = stream; 11 } 12 13 public void embark() { 14 stream.println("Embarking on quest to slay the dragon!"); 15 } 16 17 }
5.
1 package chapter01.sia.knights; 2 3 import org.springframework.context.support. 4 ClassPathXmlApplicationContext; 5 6 public class KnightMain { 7 8 public static void main(String[] args) throws Exception { 9 ClassPathXmlApplicationContext context = 10 new ClassPathXmlApplicationContext("classpath:knight.xml"); 11 Knight knight = context.getBean(Knight.class); 12 knight.embarkOnQuest(); 13 context.close(); 14 } 15 16 }
6.运行
1 三月 01, 2016 9:42:47 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 2 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4ec12ad8: startup date [Tue Mar 01 09:42:47 CST 2016]; root of context hierarchy 3 三月 01, 2016 9:42:47 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 4 信息: Loading XML bean definitions from class path resource [knight.xml] 5 三月 01, 2016 9:42:47 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose 6 信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@4ec12ad8: startup date [Tue Mar 01 09:42:47 CST 2016]; root of context hierarchy 7 Embarking on quest to slay the dragon!