参考资料完成如下程序:
(资料:Java EE 企业级应用开发教程(spring + spring MVC + MyBatis)— 黑马程序员)
(1)建立Phone接口(call方法),建立PhoneImpl实现类(call方法)。
(2)建立Student接口(learn方法),并建立StudentImpl实现类(name和phone属性,learn方法和setPhone方法)。
注:通过setPhone方法可以为phone属性赋值。
(3)使用ApplicationContext接口,实例化spring容器,并初始化(phone和student两个bean)。
(4
)将phone(bean)通过setter方法注入到student中。
(5)建立TestSpring测试类,在main方法中,进行测试。
注意:搭建Spring开发环境时第三方依赖包 commons-logging-1.2.jar 不能丢掉
代码:
public interface Phone { // 建立Phone接口
public void call();
}
public class PhoneImpl implements Phone { // 建立PhoneImpl实现类
// 实现接口Phone中的方法
@Override
public void call(){
System.out.println("手机正在拨打电话......");
}
}
public interface Student { // 建立Student接口
public void learn();
}
public class StudentImpl implements Student { //建立StudentImpl实现类
// 声明Student属性
private String name;
// 声明Phone属性
private Phone phone;
// 添加Phone属性的setter方法,用于实现依赖注入
public void setPhone(Phone phone) {
this.phone = phone;
}
// 实现接口中的方法
@Override
public void learn() {
// 调用phone中的call()方法,并输出语句
this.phone.call();
System.out.println("学生正在学习......");
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring { // 建立TestSpring测试类
public static void main(String[] args) {
// 初始化spring容器,加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// 通过容器获取Student实例
Student student = (Student) applicationContext.getBean("student");
// 调用实例中的learn()方法
student.learn();
}
}
spring 配置文件 applicationContext.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">
<!--将指定类配置给spring,让spring创建其对象的实例-->
<!-- 添加一个 id 为 Phone 的实例 -->
<bean id="phone" class="com.spring.org.PhoneImpl">
</bean>
<!-- 添加一个id为Student的实例 -->
<bean id="student" class="com.spring.org.StudentImpl">
<!-- 将 name 为 phone 的 Bean 实例注入到 Student 实例中 -->
<property name="phone" ref="phone" />
</bean>
</beans>
运行结果:
在这条路上与君共勉!