我的第一个spring程序

(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();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值