利用beans.xml进行简单的Spring应用上下文创建与使用

继上次配置Spring完成后,我们来创建一个简单的例程来理解Spring中利用beans.xml创建应用上下文的方法。

 

程序路径包为:com.spring.kinghts(kinght单词拼写错误,怕麻烦就没有重构)

首先,我们创建两个接口:Knight(英雄)与ToDo(做什么)。代码如下:

package com.spring.kinghts;

public interface Knight {
	public void doWhat();
}
package com.spring.kinghts;

public interface ToDo {
	public void toDo();
}

接下来,创建两个上述接口的实现类:Knight_guanyu(关羽)与ToDo_guanyu_drink(关羽喝酒)。代码如下:

package com.spring.kinghts;
public class Knight_guanyu implements Knight{
	private ToDo todo;
	public Knight_guanyu(ToDo todo){
		this.todo=todo;
	}
	@Override
	public void doWhat() {
		todo.toDo();
	}
}

关羽类的构造器中传入了ToDo接口引用对象,目的是为了实现依赖构造三种方法中其一(构造器依赖),以降低耦合度。

package com.spring.kinghts;
public class ToDo_guanyu_drink implements ToDo{
	@Override
	public void toDo() {
		System.out.println("我可以喝酒");
	}
}

接下来创建beans.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="com.spring.kinghts.Knight_guanyu">
		<constructor-arg ref="todo"/>
	</bean>
	
	<bean id="todo" class="com.spring.kinghts.ToDo_guanyu_drink">
	</bean>	  
</beans>

第一个<bean>中,注入了Knight_guanyu bean,第二个<bean>中,创建ToDo_guanyu_drink bean。在这里,Knight_guanyu bean在构造的时候传入了ToDo_guanyu_drink bean的引用。

最后,创建KnightMain类来加载包含Knight的Spring上下文。代码如下:

package com.spring.kinghts;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class KnightMain {
	public static void main(String[] args) throws Exception{
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		Knight_guanyu obj=(Knight_guanyu) context.getBean(Knight.class);
		obj.doWhat();
	}
}

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");作用是加载Spring上下文
Knight_guanyu obj=(Knight_guanyu) context.getBean(Knight.class);作用是获取knight bean
obj.doWhat();作用是使用knight

 

                            热爱分享拒绝拿来主义,博客精神永存——cvrigo
                                2016-11-07 23:24:37
  

 

 

posted @ 2016-11-07 23:26  Vrigo  阅读(1816)  评论(0编辑  收藏  举报