(1)在Idea中,创建一个项目,将spring的4个基础包以及commons-logging的JAR包复制到lib目录中,并发布到类路径下
(2)在src目录下,创建一个com.spring包,并在包中创建接口phone,然后在接口中定义一个call()方法
package com.spring;
public interface phone {
public void call();
}
(3)在com.spring包下,创建phone接口的实现类phoneimpl,该类需要实现接口中的call()方法,并在方法中编写一条输出语句
package com.spring;
public class phoneimpl implements phone {
public void call(){
System.out.println(“phone call hello world!”);
}
}
(4)在src目录下,创建spring的配置文件applicationcontext.xml,并在配置文件中创建一个ID为phone的Bean
(5)在com.spring包下,创建测试类test,并在类中编写main()方法。在main()方法中,需要初始化spring容器,并加载配置文件,然后通过spring容器获取phone实例,最后调用实例中的call()方法
package com.spring;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
public static void main(String[] args){
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(“applicationContext.xml”);
phone phone =(phone) applicationContext.getBean(“phone”);
phone.call();
}
}
(1)在com.spring包中,创建接口student,在接口中编写一个learn()方法
package com.spring;
public interface student {
public void learn();
}
(2)在com.spring包中,创建student接口的实现类studentimpl,在类中声明phone属性,并添加属性的setter方法
package com.spring;
public class studentimpl implements student{
private phone phone;
public void setPhone(com.spring.phone phone) {
this.phone = phone;
}
public void learn(){
this.phone.call();
System.out.println("student learn hello world!");
}
(3)在配置文件中applicationcontext.xml中,创建一个id为student的Bean,该Bean用于实例化studentimpl类的信息,并将phone的实例注入到student中
(4)在com.spring包中,创建测试类test2,来对程序进行测试package com.spring;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class test2 {
public static void main(String[] args){
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(“applicationContext.xml”);
student student =
(student) applicationContext.getBean(“student”);
student.learn();
}
}