首页 技术 正文
技术 2022年11月8日
0 收藏 457 点赞 1,479 浏览 1984 个字

继上次配置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
  

 

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295