Spring入门

1.进入springframework.org站点下载spring-framework-2.5.0-with-dependencies.zip并解压缩.

2.右击项目名,选择properties-->Java Build Path,并切换到"Libraries"标签页面,点击"Add External JARS..."将解压后的spring-

framework-2.5文件中的dist/modules/spring-core.jar和spring-beans.jar及lib/jakarta-commons/commons-logging.jar加入.

3.写一个最简单的例子
<1>.Java代码
package myspring;
public interface DeviceWriter {
public void saveData();
}

package myspring;
public class UsbDiskWriter implements DeviceWriter {
public void saveData(){
System.out.println("存储至USB!");
}
}

package myspring;
public class HelloBean {
private String helloWord;
private DeviceWriter writer;

public String getHelloWord() {
return helloWord;
}

public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}

public DeviceWriter getDeviceWriter() {
return writer;
}

public void setDeviceWriter(DeviceWriter writer) {
this.writer = writer;
}

public void saveData(){
writer.saveData();
}
}

<2>.配置文件(存放目录:WEB-INF/classes/beans-config.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-2.0.xsd">

<bean id="writer" class="myspring.UsbDiskWriter"/>

<bean id="helloBean" class="myspring.HelloBean">
<property name="helloWord">
<value>Hello! Nice to see you.</value> <!-- 注入String -->
</property>

<property name="deviceWriter">
<ref bean="writer"/> <!-- 注入自定义类(UsbDiskWriter) -->
</property>
</bean>

</beans>

<3>.测试
package myspring;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

public class SpringDemo {
public static void main(String[] args){
Resource res = new ClassPathResource("beans-config.xml");
BeanFactory factory = new XmlBeanFactory(res);
HelloBean hb = (HelloBean)factory.getBean("helloBean"); // 通过配置文件中的bean的id实例化一个对象
System.out.println("Output: "+hb.getHelloWord()); // Output: Hello! Nice to see you.
hb.saveData(); // 存储至USB!
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值